// Main app: state machine, theme provider, tweaks panel

const { useState: usM, useEffect: ueM, useMemo: umM } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "neon",
  "mode": "dark",
  "showTechFields": true,
  "shirtStyle": "realistic",
  "adminView": "table"
}/*EDITMODE-END*/;

const THEMES = {
  neon: {
    name: 'Neon Carbon',
    sub: 'Tech / racing — карбон, неон, спорт',
    vars: {
      '--bg':         '#0a0b0d',
      '--bg-2':       '#101216',
      '--surface':    '#15181d',
      '--surface-2':  '#1d2127',
      '--surface-3':  '#272c34',
      '--border':     '#2a2f37',
      '--text':       '#e8eaed',
      '--text-dim':   '#8a929c',
      '--text-faint': '#5a626c',
      '--accent':     '#00ff9c',
      '--accent-2':   '#00d4ff',
      '--danger':     '#ff3860',
      '--warn':       '#ffb000',
      '--ok':         '#00ff9c',
      '--shadow':     '0 0 0 1px rgba(0,255,156,0.08), 0 8px 32px rgba(0,0,0,0.6)',
    },
  },
  ice: {
    name: 'Glacial Ice',
    sub: 'Арктический outdoor — лёд, сталь, северное сияние',
    vars: {
      '--bg':         '#0d1419',
      '--bg-2':       '#13202b',
      '--surface':    '#1a2935',
      '--surface-2':  '#243646',
      '--surface-3':  '#2e4357',
      '--border':     '#2a3e51',
      '--text':       '#eaf3fa',
      '--text-dim':   '#92a8bb',
      '--text-faint': '#5e7589',
      '--accent':     '#7df9ff',
      '--accent-2':   '#a78bfa',
      '--danger':     '#ff5577',
      '--warn':       '#ffc850',
      '--ok':         '#7df9ff',
      '--shadow':     '0 0 0 1px rgba(125,249,255,0.1), 0 8px 32px rgba(0,12,20,0.6)',
    },
  },
  steel: {
    name: 'Industrial Steel',
    sub: 'Скандинавский минимализм — графит, сталь, жёлтый ядерный',
    vars: {
      '--bg':         '#f5f5f3',
      '--bg-2':       '#ebebe8',
      '--surface':    '#ffffff',
      '--surface-2':  '#e6e6e2',
      '--surface-3':  '#d2d2cc',
      '--border':     '#cdcdc6',
      '--text':       '#0e1114',
      '--text-dim':   '#5a626a',
      '--text-faint': '#8a929a',
      '--accent':     '#0a8f4a',
      '--accent-2':   '#ff6b00',
      '--danger':     '#d6213f',
      '--warn':       '#cc8a00',
      '--ok':         '#0a8f4a',
      '--shadow':     '0 0 0 1px rgba(0,0,0,0.06), 0 8px 24px rgba(0,0,0,0.08)',
    },
  },
  blaze: {
    name: 'Blaze Orange',
    sub: 'Rally / motorsport — глубокий чёрный, оранжевая магма',
    vars: {
      '--bg':'#0c0908','--bg-2':'#15100d','--surface':'#1c1612','--surface-2':'#261d17',
      '--surface-3':'#33271f','--border':'#3a2c22','--text':'#fbf3ec','--text-dim':'#b09a89',
      '--text-faint':'#7a6859','--accent':'#ff6b00','--accent-2':'#ffb000',
      '--danger':'#ff3050','--warn':'#ffb000','--ok':'#9be15d',
      '--shadow':'0 0 0 1px rgba(255,107,0,0.12), 0 8px 32px rgba(0,0,0,0.7)',
    },
  },
  aurora: {
    name: 'Aurora Borealis',
    sub: 'Северное сияние — фиолетовый космос, мятный акцент',
    vars: {
      '--bg':'#0a0814','--bg-2':'#10112a','--surface':'#171838','--surface-2':'#1f2148',
      '--surface-3':'#2a2c5a','--border':'#2e3168','--text':'#ecebff','--text-dim':'#9ea3d4',
      '--text-faint':'#5d62a0','--accent':'#a3ffd6','--accent-2':'#c084fc',
      '--danger':'#ff5e92','--warn':'#ffd166','--ok':'#a3ffd6',
      '--shadow':'0 0 0 1px rgba(163,255,214,0.1), 0 8px 32px rgba(8,5,30,0.7)',
    },
  },
  rust: {
    name: 'Forge Rust',
    sub: 'Кованый металл — ржавчина, медь, тёплый свет ангара',
    vars: {
      '--bg':'#1a120c','--bg-2':'#231a13','--surface':'#2c211a','--surface-2':'#372a21',
      '--surface-3':'#443429','--border':'#4a382c','--text':'#f0e4d4','--text-dim':'#b59880',
      '--text-faint':'#7a6552','--accent':'#d97757','--accent-2':'#e8b65c',
      '--danger':'#e74c3c','--warn':'#e8b65c','--ok':'#88c057',
      '--shadow':'0 0 0 1px rgba(217,119,87,0.12), 0 8px 32px rgba(0,0,0,0.6)',
    },
  },
  paper: {
    name: 'Paper & Ink',
    sub: 'Светлая редакторская — тёплый фон, зеленый акцент',
    vars: {
      '--bg':'#f7f3ec','--bg-2':'#efe9dd','--surface':'#fffdf8','--surface-2':'#ebe5d6',
      '--surface-3':'#dcd4c2','--border':'#d4ccb8','--text':'#1c1a14','--text-dim':'#5d574a',
      '--text-faint':'#8a8472','--accent':'#0a8f4a','--accent-2':'#ff6b00',
      '--danger':'#d92e58','--warn':'#c98a00','--ok':'#1a8b5e',
      '--shadow':'0 0 0 1px rgba(0,0,0,0.06), 0 8px 24px rgba(28,26,20,0.08)',
    },
  },
};

const FONT_HEADINGS = {
  rajdhani: { family: "'Rajdhani', sans-serif", url: 'Rajdhani:wght@500;600;700' },
  oswald:   { family: "'Oswald', sans-serif",   url: 'Oswald:wght@500;700' },
  syncopate:{ family: "'Syncopate', sans-serif",url: 'Syncopate:wght@400;700' },
};
const FONT_BODIES = {
  inter:    { family: "'Inter', sans-serif",    url: 'Inter:wght@400;500;600' },
  ibm:      { family: "'IBM Plex Sans', sans-serif", url: 'IBM+Plex+Sans:wght@400;500;600' },
  jetbrains:{ family: "'JetBrains Mono', monospace", url: 'JetBrains+Mono:wght@400;500;600' },
};

function applyTheme(t) {
  const theme = THEMES[t] || THEMES.neon;
  Object.entries(theme.vars).forEach(([k,v]) => document.documentElement.style.setProperty(k, v));
  document.documentElement.dataset.theme = t;
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = usM(NordicrewCore.hasAdminSession() ? 'admin' : 'login'); // login | dashboard | editor | preview | admin
  const [userId, setUserId] = usM(null);
  const [shirtId, setShirtId] = usM(null);
  const [adminImpersonating, setAdminImpersonating] = usM(null);
  const [kitState, setKitState] = usM(() => NordicrewCore.loadState({
    users: SAMPLE_USERS,
    shirts: SHIRTS,
    customLogos: [],
    templates: DEFAULT_TEMPLATES,
    defaultTemplate: null,
  }));

  const users = kitState.users;
  const shirts = kitState.shirts;
  const customLogos = kitState.customLogos || [];
  const defaultTemplate = kitState.defaultTemplate || null;
  const templates = kitState.templates || [];

  ueM(() => {
    let cancelled = false;
    if (!window.NordicrewApi) return;
    NordicrewApi.loadState()
      .then(remoteState => {
        if (cancelled) return;
        if (remoteState) {
          setKitState(NordicrewCore.saveState({
            ...remoteState,
            templates: remoteState.templates || DEFAULT_TEMPLATES,
          }));
        } else {
          NordicrewApi.saveState(kitState).catch(() => {});
        }
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  const persistKitState = (producer) => {
    setKitState(prev => {
      const draft = typeof producer === 'function' ? producer(NordicrewCore.clone(prev)) : producer;
      const saved = NordicrewCore.saveState(draft);
      if (window.NordicrewApi) NordicrewApi.saveState(saved).catch(() => {});
      return saved;
    });
  };

  const setShirts = (updater) => {
    persistKitState(prev => ({
      ...prev,
      shirts: typeof updater === 'function' ? updater(prev.shirts) : updater,
    }));
  };

  const resetKitState = () => {
    const fresh = NordicrewCore.createState({ users: SAMPLE_USERS, shirts: SHIRTS, customLogos: [], templates: DEFAULT_TEMPLATES, defaultTemplate: null });
    setKitState(NordicrewCore.saveState(fresh));
    if (window.NordicrewApi) NordicrewApi.saveState(fresh).catch(() => {});
    setUserId(null);
    setShirtId(null);
    setView('admin');
  };

  // Apply the default template to ALL shirts that are still 'empty' and have no designs
  const applyTemplateToAll = (tpl) => {
    persistKitState(prev => {
      const next = { ...prev.shirts };
      Object.keys(next).forEach(sid => {
        const s = next[sid];
        const isEmpty = !s.designs || (
          (s.designs.front||[]).length === 0 &&
          (s.designs.back||[]).length === 0 &&
          (s.designs.sleeve||[]).length === 0
        );
        if (s.status !== 'done' && (isEmpty || tpl === null)) {
          const user = prev.users.find(u => u.id === s.userId);
          next[sid] = { ...s, designs: tpl ? applyTemplate(tpl, user, s.color) : { front: [], back: [], sleeve: [] } };
        }
      });
      return { ...prev, shirts: next, defaultTemplate: tpl };
    });
  };

  // Effective theme: 'mode' light/dark forces a base theme, otherwise the named theme is used
  const effectiveTheme = tweaks.mode === 'light'
    ? (tweaks.theme === 'paper' || tweaks.theme === 'steel' ? tweaks.theme : 'paper')
    : (tweaks.theme === 'paper' || tweaks.theme === 'steel' ? 'neon' : tweaks.theme);

  ueM(() => applyTheme(effectiveTheme), [effectiveTheme]);
  ueM(() => {
    document.documentElement.style.setProperty('--font-heading', "'Inter', sans-serif");
    document.documentElement.style.setProperty('--font-body', "'Inter', sans-serif");
  }, []);
  ueM(() => {
    document.documentElement.dataset.shirtStyle = tweaks.shirtStyle || 'realistic';
  }, [tweaks.shirtStyle]);

  const toggleMode = () => setTweak('mode', tweaks.mode === 'light' ? 'dark' : 'light');
  // Expose toggle so deep child components (TopBar, AdminPanel) can render an inline button
  window.__toggleThemeMode = toggleMode;
  window.__themeMode = tweaks.mode;

  const onLogin = (uid) => { setUserId(uid); setView('dashboard'); };
  const onAdminLogin = () => { NordicrewCore.saveAdminSession(); setView('admin'); };
  const onLogout = () => { NordicrewCore.clearAdminSession(); setUserId(null); setShirtId(null); setAdminImpersonating(null); setView('login'); };
  const openShirt = (sid) => { setShirtId(sid); setView('editor'); };
  const onImpersonate = (uid) => { setAdminImpersonating(true); setUserId(uid); setView('dashboard'); };
  const exitImpersonation = () => { setAdminImpersonating(false); setUserId(null); setShirtId(null); setView('admin'); };
  const submitUserKit = () => {
    persistKitState(prev => NordicrewCore.submitUserKit(prev, userId));
  };
  const addUser = (data) => persistKitState(prev => NordicrewCore.addUser(prev, data));
  const addShirt = (uid, data) => persistKitState(prev => NordicrewCore.addShirt(prev, uid, data));
  const updateUser = (uid, patch) => persistKitState(prev => NordicrewCore.updateUser(prev, uid, patch));
  const addLogo = (logo) => persistKitState(prev => ({ ...prev, customLogos: [...(prev.customLogos || []), logo] }));
  const saveTemplate = (template) => persistKitState(prev => {
    const normalized = NordicrewCore.normalizeTemplate(template, prev.templates?.length || 0);
    const exists = (prev.templates || []).some(t => t.id === normalized.id);
    return {
      ...prev,
      templates: exists
        ? prev.templates.map(t => t.id === normalized.id ? normalized : t)
        : [...(prev.templates || []), normalized],
    };
  });
  const deleteTemplate = (templateId) => persistKitState(prev => ({
    ...prev,
    templates: (prev.templates || []).length > 1
      ? prev.templates.filter(t => t.id !== templateId)
      : prev.templates,
  }));
  const applyUserTemplate = (templateId) => {
    const tpl = templates.find(t => t.id === templateId);
    if (!tpl || !user) return;
    persistKitState(prev => {
      const next = { ...prev.shirts };
      user.shirts.forEach(sid => {
        const shirt = next[sid];
        if (!shirt || shirt.status === 'done') return;
        next[sid] = {
          ...shirt,
          designs: applyTemplate(tpl.designs, user, shirt.color),
          status: 'in-progress',
          updatedAt: new Date().toISOString().slice(0,10),
        };
      });
      return { ...prev, shirts: next };
    });
  };
  const importState = (jsonText) => {
    const parsed = NordicrewCore.parseImportedJson(jsonText);
    persistKitState(prev => ({
      ...prev,
      users: parsed.users || prev.users,
      shirts: parsed.shirts || prev.shirts,
      customLogos: parsed.customLogos || prev.customLogos || [],
      defaultTemplate: parsed.defaultTemplate !== undefined ? parsed.defaultTemplate : prev.defaultTemplate,
    }));
  };

  const user = userId ? users.find(u => u.id === userId) : null;
  const idx = user && shirtId ? user.shirts.indexOf(shirtId) : -1;
  const hasNext = user && idx >= 0 && idx < user.shirts.length - 1;
  const hasPrev = user && idx > 0;

  return (
    <div className="app" data-theme={effectiveTheme} data-mode={tweaks.mode} data-shirt-style={tweaks.shirtStyle || 'realistic'}>
      {adminImpersonating && view !== 'admin' && (
        <div className="impersonation-bar">
          <span>👁 ВЫ ВОШЛИ КАК <b>{user?.nickname}</b> · {user?.email}</span>
          <button className="btn ghost xsmall" onClick={exitImpersonation}>← ВЕРНУТЬСЯ В АДМИНКУ</button>
        </div>
      )}
      {view === 'login' && <LoginScreen users={users} onLogin={onLogin} onAdminLogin={onAdminLogin}/>}
      {view === 'dashboard' && user && (
        <UserDashboard users={users} shirts={shirts} customLib={customLogos} templates={templates}
                       userId={userId} onOpenShirt={openShirt} onApplyTemplate={applyUserTemplate}
                       onPreview={() => setView('preview')}
                       onLogout={adminImpersonating ? exitImpersonation : onLogout}/>
      )}
      {view === 'editor' && user && shirtId && (
        <EditorScreen users={users} customLib={customLogos} userId={userId} shirtId={shirtId}
                      shirts={shirts} setShirts={setShirts}
                      onBack={() => setView('dashboard')}
                      onNextShirt={() => setShirtId(user.shirts[idx+1])}
                      onPrevShirt={() => setShirtId(user.shirts[idx-1])}
                      hasNext={hasNext} hasPrev={hasPrev}
                      showTechFields={tweaks.showTechFields}/>
      )}
      {view === 'preview' && user && (
        <PreviewScreen users={users} userId={userId} shirts={shirts} customLib={customLogos}
                       onBack={() => setView('dashboard')}
                       onSubmit={submitUserKit}/>
      )}
      {view === 'admin' && (
        <AdminPanel users={users} shirts={shirts} customLib={customLogos}
                    onLogout={onLogout} onImpersonate={onImpersonate}
                    defaultTemplate={defaultTemplate} templates={templates}
                    onApplyTemplate={applyTemplateToAll} onSaveTemplate={saveTemplate} onDeleteTemplate={deleteTemplate}
                    onAddUser={addUser} onAddShirt={addShirt} onUpdateUser={updateUser}
                    onAddLogo={addLogo} onImportState={importState} onResetState={resetKitState}/>
      )}

      <TweaksPanel title="Tweaks">
          <TweakSection title="Режим">
            <TweakRadio value={tweaks.mode} onChange={v => setTweak('mode', v)}
                        options={[
                          { value: 'dark',  label: '☾ Тёмная' },
                          { value: 'light', label: '☀ Светлая' },
                        ]}/>
          </TweakSection>
          <TweakSection title="Тема (тёмная)">
            <TweakSelect value={tweaks.theme} onChange={v => setTweak('theme', v)}
                         options={[
                           { value: 'neon',   label: 'Neon Carbon — tech/racing' },
                           { value: 'ice',    label: 'Glacial Ice — арктика' },
                           { value: 'blaze',  label: 'Blaze Orange — rally' },
                           { value: 'aurora', label: 'Aurora — северное сияние' },
                           { value: 'rust',   label: 'Forge Rust — кованый металл' },
                           { value: 'steel',  label: 'Industrial Steel — светлая' },
                           { value: 'paper',  label: 'Paper & Ink — кремовая' },
                         ]}/>
            <div className="tweak-theme-desc">{THEMES[effectiveTheme]?.sub}</div>
          </TweakSection>
          <TweakSection title="Стиль футболки">
            <TweakRadio value={tweaks.shirtStyle || 'realistic'} onChange={v => setTweak('shirtStyle', v)}
                        options={[
                          { value: 'realistic', label: '◐ Реалистичный' },
                          { value: 'technical', label: '⊟ Технический' },
                        ]}/>
          </TweakSection>
          <TweakSection title="Технические поля">
            <TweakToggle label="Координаты в мм / поворот°" value={tweaks.showTechFields}
                         onChange={v => setTweak('showTechFields', v)}/>
          </TweakSection>
          <TweakSection title="Быстрая навигация">
            <div className="tweak-nav">
              <button className="btn ghost xsmall" onClick={() => { setUserId('u1'); setView('dashboard'); }}>→ Дашборд</button>
              <button className="btn ghost xsmall" onClick={() => { setUserId('u2'); setShirtId('s5'); setView('editor'); }}>→ Редактор</button>
              <button className="btn ghost xsmall" onClick={() => { setUserId('u1'); setView('preview'); }}>→ Превью</button>
              <button className="btn ghost xsmall" onClick={() => setView('admin')}>→ Админ</button>
              <button className="btn ghost xsmall" onClick={() => setView('login')}>→ Логин</button>
            </div>
          </TweakSection>
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
