// Main App shell — routing, navigation, language, role, tweaks
const { useState: aState, useEffect: aEffect, useMemo: aMemo, useRef: aRef } = React;

// Apply accent color to CSS variables
function applyAccent(hex) {
  const root = document.documentElement;
  root.style.setProperty('--accent', hex);
  root.style.setProperty('--accent-soft', `color-mix(in oklab, ${hex} 14%, var(--bg))`);
  root.style.setProperty('--accent-strong', `color-mix(in oklab, ${hex} 75%, #000)`);
}

const NAV = [
  { key: 'dashboard', label: 'nav_dashboard', icon: 'Dashboard', section: 'overview' },
  { key: 'stock', label: 'nav_stock', icon: 'Box', section: 'overview' },
  { key: 'movement', label: 'nav_movement', icon: 'Move', section: 'overview' },
  { key: 'suggested', label: 'nav_actions', icon: 'Sparkle', section: 'overview', badge: true },
  { key: 'reports', label: 'nav_reports', icon: 'Chart', section: 'overview' },
  { key: 'settings', label: 'nav_settings', icon: 'Gear', section: 'admin' }
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "density": "comfortable",
  "accent": "#B45518",
  "role": "officer",
  "nav": "side",
  "dashLayout": "A",
  "lang": "th"
}/*EDITMODE-END*/;

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [route, setRoute] = aState('dashboard');
  const [routeState, setRouteState] = aState({});
  const [drawerProduct, setDrawerProduct] = aState(null);
  const [movementModal, setMovementModal] = aState(null); // { type, product }

  const lang = tweaks.lang || 'th';
  const t = window.CKW_I18N[lang];

  const { state, dispatch } = useStore();

  // Apply theme/density/accent on tweak changes
  aEffect(() => {
    document.documentElement.setAttribute('data-theme', tweaks.theme);
    document.documentElement.setAttribute('data-density', tweaks.density);
    applyAccent(tweaks.accent);
    document.documentElement.setAttribute('lang', lang);
  }, [tweaks.theme, tweaks.density, tweaks.accent, lang]);

  function navigate(key, st) {
    setRoute(key);
    setRouteState(st || {});
    window.scrollTo(0, 0);
  }

  function openMovement(type, product) {
    setMovementModal({ type, product });
  }

  const attentionCount = aMemo(
    () => state.products.filter(p => p.status === 'low' || p.status === 'out').length,
    [state.products]
  );

  // Always-current drawer product (so list updates flow through)
  const liveDrawer = drawerProduct ? (state.products.find(p => p.sku === drawerProduct.sku) || drawerProduct) : null;

  return (
    <div className="app" data-nav={tweaks.nav}>
      {tweaks.nav === 'side' ? (
        <Sidebar
          t={t} lang={lang} route={route} navigate={navigate}
          tweaks={tweaks} setTweak={setTweak}
          attentionCount={attentionCount}
        />
      ) : (
        <TopNav
          t={t} lang={lang} route={route} navigate={navigate}
          tweaks={tweaks} setTweak={setTweak}
          attentionCount={attentionCount}
        />
      )}

      <div className="main">
        {tweaks.nav === 'side' && (
          <Topbar t={t} lang={lang} tweaks={tweaks} setTweak={setTweak} />
        )}

        {route === 'dashboard' && <Dashboard t={t} lang={lang} role={tweaks.role} layoutVariant={tweaks.dashLayout} onNav={navigate} />}
        {route === 'stock' && <StockList
          t={t} lang={lang} role={tweaks.role} density={tweaks.density}
          initialFilter={routeState.filter} focusSku={routeState.focus}
          onOpenDetail={(p) => setDrawerProduct(p)}
          onMovement={openMovement}
        />}
        {route === 'movement' && <MovementsScreen t={t} lang={lang} role={tweaks.role} onOpenModal={(type) => openMovement(type)} />}
        {route === 'suggested' && <SuggestedActions t={t} lang={lang} role={tweaks.role} onOpenDetail={(p) => setDrawerProduct(p)} onMovement={openMovement} />}
        {route === 'reports' && <Reports t={t} lang={lang} />}
        {route === 'settings' && <Settings t={t} lang={lang} role={tweaks.role} prefs={tweaks} setPref={setTweak} />}
      </div>

      {/* Drawer */}
      {liveDrawer && (
        <ProductDetail
          key={liveDrawer.sku}
          product={liveDrawer}
          t={t} lang={lang}
          role={tweaks.role}
          onClose={() => setDrawerProduct(null)}
          onMovement={(type, p) => openMovement(type, p || liveDrawer)}
          onUpdate={(patch) => dispatch({ type: 'UPDATE_PRODUCT', sku: liveDrawer.sku, patch })}
          onDelete={() => { dispatch({ type: 'DELETE_PRODUCTS', skus: [liveDrawer.sku] }); setDrawerProduct(null); }}
        />
      )}

      {/* Movement modal */}
      {movementModal && (
        <MovementModal
          initialType={movementModal.type}
          initialProduct={movementModal.product}
          t={t} lang={lang}
          onClose={() => setMovementModal(null)}
        />
      )}

      {/* Tweaks panel — self-manages visibility via host */}
      <TweaksPanel title={t.tweak_title}>
        <TweakSection label={t.tweak_lang} />
        <TweakRadio label="" value={tweaks.lang}
          options={[{value:'th',label:'ไทย'},{value:'en',label:'English'}]}
          onChange={v => setTweak('lang', v)} />
        <TweakSection label={t.tweak_theme} />
        <TweakRadio label="" value={tweaks.theme}
          options={[{value:'light',label:t.theme_light},{value:'dark',label:t.theme_dark}]}
          onChange={v => setTweak('theme', v)} />
        <TweakSection label={t.tweak_density} />
        <TweakRadio label="" value={tweaks.density}
          options={[{value:'comfortable',label:t.density_comfortable},{value:'compact',label:t.density_compact}]}
          onChange={v => setTweak('density', v)} />
        <TweakSection label={t.tweak_accent} />
        <TweakColor label="" value={tweaks.accent}
          options={['#B45518','#A87B1F','#0F62FE','#0E7C66','#7C3AED','#111827']}
          onChange={v => setTweak('accent', v)} />
        <TweakSection label={t.tweak_nav} />
        <TweakRadio label="" value={tweaks.nav}
          options={[{value:'side',label:t.nav_side},{value:'top',label:t.nav_top}]}
          onChange={v => setTweak('nav', v)} />
        <TweakSection label={t.tweak_dashboard} />
        <TweakRadio label="" value={tweaks.dashLayout}
          options={[{value:'A',label:t.dash_a},{value:'B',label:t.dash_b}]}
          onChange={v => setTweak('dashLayout', v)} />
        <TweakSection label={t.tweak_role} />
        <TweakSelect label="" value={tweaks.role}
          options={[{value:'officer',label:t.role_officer},{value:'manager',label:t.role_manager},{value:'sales',label:t.role_sales}]}
          onChange={v => setTweak('role', v)} />
      </TweaksPanel>
    </div>
  );
}

// ---------- Sidebar ----------
function Sidebar({ t, lang, route, navigate, tweaks, setTweak, attentionCount }) {
  const items = NAV.filter(n => n.section === 'overview');
  const adminItems = NAV.filter(n => n.section === 'admin');
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <div className="brand-mark">{t.brand_short}</div>
        <div>
          <div className="brand-name">{t.brand_name}</div>
          <div className="brand-sub">{t.brand_sub}</div>
        </div>
      </div>
      <div className="nav">
        <div className="nav-section">{t.nav_overview}</div>
        {items.map(n => {
          const IconComp = Icon[n.icon];
          return (
            <button key={n.key} className={"nav-item " + (route === n.key ? 'active' : '')} onClick={() => navigate(n.key)}>
              <IconComp className="icon" />
              <span>{t[n.label]}</span>
              {n.badge && attentionCount > 0 && <span className="nav-badge">{attentionCount}</span>}
            </button>
          );
        })}
        <div className="nav-section">{t.nav_admin}</div>
        {adminItems.map(n => {
          const IconComp = Icon[n.icon];
          return (
            <button key={n.key} className={"nav-item " + (route === n.key ? 'active' : '')} onClick={() => navigate(n.key)}>
              <IconComp className="icon" />
              <span>{t[n.label]}</span>
            </button>
          );
        })}
      </div>
      <div className="sidebar-foot">
        <RoleSwitch t={t} role={tweaks.role} setRole={(v) => setTweak('role', v)} />
      </div>
    </aside>
  );
}

// ---------- Top nav variant ----------
function TopNav({ t, lang, route, navigate, tweaks, setTweak, attentionCount }) {
  const items = NAV.filter(n => n.section === 'overview');
  const adminItems = NAV.filter(n => n.section === 'admin');
  return (
    <header className="topbar-nav">
      <div className="brand-mark">{t.brand_short}</div>
      <div style={{ marginLeft: 12 }}>
        <div className="brand-name" style={{ fontSize: 14 }}>{t.brand_name}</div>
        <div className="brand-sub">{t.brand_sub}</div>
      </div>
      <div className="nav-items">
        {[...items, ...adminItems].map(n => {
          const IconComp = Icon[n.icon];
          return (
            <button key={n.key} className={"nav-item " + (route === n.key ? 'active' : '')} onClick={() => navigate(n.key)}>
              <IconComp className="icon icon-sm" />
              <span>{t[n.label]}</span>
              {n.badge && attentionCount > 0 && <span className="nav-badge">{attentionCount}</span>}
            </button>
          );
        })}
      </div>
      <div className="row" style={{ gap: 8 }}>
        <LangSwitch lang={tweaks.lang} setLang={(v) => setTweak('lang', v)} />
        <RoleSwitch t={t} role={tweaks.role} setRole={(v) => setTweak('role', v)} compact />
      </div>
    </header>
  );
}

// ---------- Topbar ----------
function Topbar({ t, lang, tweaks, setTweak }) {
  return (
    <div className="topbar">
      <Icon.Search className="icon icon-sm" style={{ color: 'var(--ink-3)' }} />
      <input
        placeholder={t.search_placeholder}
        style={{ background: 'transparent', border: 0, outline: 0, fontSize: 14, width: 360 }}
      />
      <span className="topbar-spacer"></span>
      <LangSwitch lang={tweaks.lang} setLang={(v) => setTweak('lang', v)} />
      <button className="btn-icon btn-ghost" title={t.notifications} style={{ position: 'relative' }}>
        <Icon.Bell className="icon" />
        <span style={{ position: 'absolute', top: 6, right: 6, width: 8, height: 8, background: 'var(--bad)', borderRadius: '50%', border: '2px solid var(--surface)' }}></span>
      </button>
      <div className="row" style={{ gap: 8, padding: '4px 12px 4px 4px', background: 'var(--surface-2)', borderRadius: 999 }}>
        <div className="avatar">SP</div>
        <div style={{ fontSize: 13 }}>
          <div style={{ fontWeight: 600, lineHeight: 1 }}>{lang === 'th' ? 'สมพร' : 'Somporn'}</div>
          <div className="t-muted" style={{ fontSize: 11 }}>{t['role_' + tweaks.role]}</div>
        </div>
      </div>
    </div>
  );
}

function LangSwitch({ lang, setLang }) {
  return (
    <div className="segmented" style={{ padding: 2 }}>
      <button className={lang === 'th' ? 'active' : ''} onClick={() => setLang('th')}>
        <Icon.Globe className="icon icon-sm" style={{ marginRight: 4 }} /> ไทย
      </button>
      <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
    </div>
  );
}

function RoleSwitch({ t, role, setRole, compact }) {
  const roles = [
    { key: 'officer', label: t.role_officer, icon: <Icon.Box className="icon icon-sm" /> },
    { key: 'manager', label: t.role_manager, icon: <Icon.User className="icon icon-sm" /> },
    { key: 'sales', label: t.role_sales, icon: <Icon.Tag className="icon icon-sm" /> }
  ];
  const current = roles.find(r => r.key === role) || roles[0];
  const [open, setOpen] = aState(false);
  const ref = aRef();
  useOutsideClick(ref, () => setOpen(false));
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} className="btn" style={{ width: compact ? 'auto' : '100%', justifyContent: 'flex-start' }}>
        {current.icon}
        <span style={{ flex: 1, textAlign: 'left' }}>{current.label}</span>
        <Icon.ArrowDown className="icon icon-sm" />
      </button>
      {open && (
        <div className="menu" style={{ bottom: compact ? 'auto' : '52px', top: compact ? '46px' : 'auto', left: 0, right: compact ? 0 : 'auto', minWidth: 180 }}>
          {roles.map(r => (
            <button key={r.key} onClick={() => { setRole(r.key); setOpen(false); }}>
              {r.icon} {r.label}
              {role === r.key && <span style={{ marginLeft: 'auto' }}><Icon.Check className="icon icon-sm" style={{ color: 'var(--accent)' }} /></span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

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