// EMPHASIS Tracking System — main app shell with auth, 7 modules, UL/DL widgets.

const STORAGE_KEY = 'emphasis.config.v1';
const SESSION_KEY = 'emphasis.session.v1';

function loadConfig() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) || null; } catch { return null; }
}
function saveConfig(cfg) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(cfg)); } catch {}
}
function loadSession() {
  try { return JSON.parse(localStorage.getItem(SESSION_KEY)) || null; } catch { return null; }
}
function saveSession(u) {
  try { localStorage.setItem(SESSION_KEY, JSON.stringify(u)); } catch {}
}
function clearSession() {
  try { localStorage.removeItem(SESSION_KEY); } catch {}
}

function App() {
  const [session, setSession] = useState(loadSession());
  const [view, setView] = useState('calendar');
  const [, forceRerender] = useState(0);

  // Re-render when Supabase data lands so badges + lists reflect the live mode
  useEffect(() => {
    const onReady = () => forceRerender(n => n + 1);
    window.addEventListener('emphasis:data-ready', onReady);
    return () => window.removeEventListener('emphasis:data-ready', onReady);
  }, []);

  // Live-editable config (appointment types + lead sources).
  const initial = loadConfig();
  const [apptTypes, setApptTypes] = useState(initial?.apptTypes || window.APPT_TYPES);
  const [leadSources, setLeadSources] = useState(initial?.leadSources || window.LEAD_SOURCES);

  // Focus DLs — selected 5 DLs to spotlight in sidebar
  const [focusIds, setFocusIds] = useState(() => {
    const saved = initial?.focusIds;
    if (saved) return saved;
    return window.ABO_LIST.filter(a => a.focus).slice(0, 5).map(a => a.id);
  });

  useEffect(() => {
    saveConfig({ apptTypes, leadSources, focusIds });
    window.APPT_TYPES = apptTypes;
    window.LEAD_SOURCES = leadSources;
  }, [apptTypes, leadSources, focusIds]);

  const handleLogin = (user) => { setSession(user); saveSession(user); };
  const handleLogout = () => { clearSession(); setSession(null); };

  const resetDefaults = () => {
    localStorage.removeItem(STORAGE_KEY);
    setApptTypes(window.__DEFAULT_APPT_TYPES);
    setLeadSources(window.__DEFAULT_LEAD_SOURCES);
  };

  if (!session) {
    return <LoginView onLogin={handleLogin} />;
  }

  const currentUser = { ...TEAM[0], ...session };

  const configValue = {
    apptTypes, setApptTypes,
    leadSources, setLeadSources,
    focusIds, setFocusIds,
    statuses: window.STATUS,
    resetDefaults,
  };

  const NAV = [
    { id: 'calendar', icon: 'calendar', label: 'EM Calendar',      sub: 'ลงตารางงาน' },
    { id: '6w',       icon: 'activity', label: '6W Tracking',      sub: 'ข้อมูลลูกค้าลดน้ำหนัก' },
    { id: 'abo',      icon: 'users',    label: 'ABO Tracking',     sub: 'DL Active ในระบบ' },
    { id: 'social',   icon: 'share-2',  label: 'Social Dashboard', sub: 'Engagement + Content' },
    { id: 'emphasis', icon: 'book',     label: 'Emphasis System',  sub: 'EM Pack · Slide · BT' },
    { id: 'admin',    icon: 'shield',   label: 'Administrator',    sub: 'Broadcast + กิจกรรม' },
    { id: 'settings', icon: 'settings', label: 'Setting',          sub: 'ตั้งค่าทุกอย่าง' },
  ];

  const viewLabel = NAV.find(n => n.id === view)?.label || '';

  return (
    <ConfigContext.Provider value={configValue}>
      <div className="min-h-screen flex" data-screen-label={`Emphasis · ${viewLabel}`}>
        {/* Sidebar */}
        <aside className="hidden md:flex flex-col w-[256px] bg-white border-r border-ink-100 flex-shrink-0 sticky top-0 h-screen">
          <div className="px-5 pt-5 pb-3 border-b border-ink-100">
            <div className="flex items-center gap-2.5">
              <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-ink-900 to-brand-700 flex items-center justify-center text-white font-bold relative overflow-hidden">
                <span className="text-sm relative z-10">E</span>
                <div className="absolute top-0 right-0 w-3 h-3 bg-gold-400 rounded-full -mt-0.5 -mr-0.5" />
              </div>
              <div>
                <div className="text-sm font-bold text-ink-900 leading-none">EMPHASIS</div>
                <div className="text-[10px] text-ink-400 tracking-wide mt-0.5">Tracking System</div>
              </div>
            </div>
          </div>

          <nav className="px-3 pt-4 pb-3 flex-1 overflow-y-auto scroll-thin">
            <div className="text-[10px] uppercase tracking-wider text-ink-400 px-3 pb-2 font-semibold">Modules</div>
            <ul className="space-y-0.5">
              {NAV.map(n => (
                <li key={n.id}>
                  <button
                    onClick={() => setView(n.id)}
                    className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                      view === n.id
                        ? 'bg-ink-900 text-white'
                        : 'text-ink-600 hover:bg-ink-50 hover:text-ink-900'
                    }`}
                  >
                    <Icon name={n.icon} className="w-4 h-4 flex-shrink-0" strokeWidth={view === n.id ? 2 : 1.75} />
                    <div className="flex-1 text-left min-w-0">
                      <div className="leading-tight truncate">{n.label}</div>
                      <div className={`text-[10px] leading-tight truncate ${view === n.id ? 'text-white/60' : 'text-ink-400'}`}>{n.sub}</div>
                    </div>
                  </button>
                </li>
              ))}
            </ul>

            {/* === Upline list === */}
            <UplinePanel />

            {/* === Focus 5 DL === */}
            <DownlineFocusPanel focusIds={focusIds} setFocusIds={setFocusIds} />
          </nav>

          {/* User chip */}
          <div className="px-3 pb-4 pt-3 border-t border-ink-100">
            <div className="flex items-center gap-2.5 px-3">
              <Avatar user={currentUser} size={34} />
              <div className="flex-1 min-w-0">
                <div className="text-xs font-semibold text-ink-900 truncate">{currentUser.name}</div>
                <div className="text-[10px] text-ink-400">BT · 18% Pace</div>
              </div>
              <button onClick={handleLogout} title="ออกจากระบบ" className="text-ink-400 hover:text-rose-600">
                <Icon name="arrowR" className="w-4 h-4" />
              </button>
            </div>
          </div>
        </aside>

        {/* Main */}
        <main className="flex-1 min-w-0 flex flex-col">
          <header className="sticky top-0 z-20 bg-white/90 backdrop-blur border-b border-ink-100">
            <div className="px-6 lg:px-8 h-14 flex items-center justify-between gap-4">
              <div className="flex items-center gap-3 min-w-0">
                <h1 className="text-base font-semibold text-ink-900 truncate">{viewLabel}</h1>
                <Pill color="#06C755" tint="#E7F8F1" size="xs" icon={<span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />}>
                  LINE Connected
                </Pill>
                {window.EMPHASIS_ENV?.banner && (
                  <Pill color="#B87C00" tint="#FFECB8" size="xs">⚙️ DEV</Pill>
                )}
                {!window.SB_READY && (
                  <Pill color="#94A3B8" tint="#F1F5F9" size="xs" icon={<Icon name="info" className="w-3 h-3" />}>No DB</Pill>
                )}
                {window.SB_READY && window.DATA_MODE === 'live' && (
                  <Pill color="#10B981" tint="#E7F8F1" size="xs" icon={<Icon name="check" className="w-3 h-3" />}>Live DB</Pill>
                )}
                {window.SB_READY && (window.DATA_MODE === 'empty' || window.DATA_MODE === 'mock-fallback') && (
                  <Pill color="#F59E0B" tint="#FFF6E0" size="xs" icon={<Icon name="info" className="w-3 h-3" />}>DB empty · run schema.sql</Pill>
                )}
              </div>
              <div className="flex items-center gap-2">
                <div className="hidden md:flex items-center gap-2 h-9 px-3 rounded-lg border border-ink-200 bg-white">
                  <Icon name="search" className="w-3.5 h-3.5 text-ink-400" />
                  <input className="text-xs outline-none w-44 bg-transparent placeholder-ink-300" placeholder="ค้นหา prospect / นัด / member..." />
                  <kbd className="text-[10px] num text-ink-400 bg-ink-100 px-1 rounded">⌘K</kbd>
                </div>
                <button className="relative w-9 h-9 rounded-lg border border-ink-200 flex items-center justify-center text-ink-500 hover:bg-ink-50">
                  <Icon name="bell" className="w-4 h-4" />
                  <span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-rose-500" />
                </button>
                <button onClick={() => setView('settings')} className="w-9 h-9 rounded-lg border border-ink-200 flex items-center justify-center text-ink-500 hover:bg-ink-50">
                  <Icon name="settings" className="w-4 h-4" />
                </button>
                <Avatar user={currentUser} size={32} ring />
              </div>
            </div>
          </header>

          <div className="flex-1 px-6 lg:px-8 py-6">
            {view === 'calendar' && <CalendarView         currentUser={currentUser} />}
            {view === '6w'       && <SixWView             />}
            {view === 'abo'      && <AboView              />}
            {view === 'social'   && <SocialView           />}
            {view === 'emphasis' && <EmphasisSystemView   currentUser={currentUser} />}
            {view === 'admin'    && <AdminView            currentUser={currentUser} />}
            {view === 'settings' && <SettingsView         />}
          </div>

          <footer className="px-6 lg:px-8 py-4 border-t border-ink-100 bg-white">
            <div className="flex items-center justify-between text-[11px] text-ink-400">
              <div>EMPHASIS Tracking System · prototype · {new Date().toLocaleDateString('th-TH', { year: 'numeric', month: 'short', day: 'numeric' })}</div>
              <div className="flex items-center gap-4">
                <span>v0.3 · prototype</span>
                <span>·</span>
                <button className="hover:text-ink-700">Docs</button>
                <button className="hover:text-ink-700">Support</button>
              </div>
            </div>
          </footer>
        </main>
      </div>
    </ConfigContext.Provider>
  );
}

// ============== Sidebar widget: Upline list ==============
function UplinePanel() {
  const [openId, setOpenId] = useState(null);
  return (
    <div className="mt-5">
      <div className="text-[10px] uppercase tracking-wider text-ink-400 px-3 pb-2 font-semibold flex items-center justify-between">
        <span>Upline · ดูตาราง</span>
        <Icon name="chevD" className="w-3 h-3 text-ink-300" />
      </div>
      <ul className="space-y-0.5">
        {window.UPLINES.map(u => (
          <li key={u.id}>
            <button onClick={() => setOpenId(openId === u.id ? null : u.id)}
              className="w-full flex items-center gap-2 px-3 py-1.5 hover:bg-ink-50 rounded-md text-left">
              <div className="relative">
                <Avatar user={u} size={24} />
                <span className={`absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full border border-white ${u.online ? 'bg-emerald-500' : 'bg-ink-300'}`} />
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-xs text-ink-800 font-medium truncate">{u.name}</div>
                <div className="text-[9px] text-ink-400 truncate">{u.pin} · {u.org}</div>
              </div>
              <Icon name="calendar" className="w-3 h-3 text-ink-300" />
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

// ============== Sidebar widget: Focus 5 DL ==============
function DownlineFocusPanel({ focusIds, setFocusIds }) {
  const [picking, setPicking] = useState(false);
  const focused = window.ABO_LIST.filter(a => focusIds.includes(a.id)).slice(0, 5);

  const toggle = (id) => {
    if (focusIds.includes(id)) {
      setFocusIds(focusIds.filter(x => x !== id));
    } else if (focusIds.length < 5) {
      setFocusIds([...focusIds, id]);
    }
  };

  return (
    <div className="mt-5">
      <div className="text-[10px] uppercase tracking-wider text-ink-400 px-3 pb-2 font-semibold flex items-center justify-between">
        <span>Focus 5 · Downline</span>
        <button onClick={() => setPicking(true)} className="text-brand-600 hover:text-brand-800 text-[10px] font-medium">
          เลือก ({focused.length}/5)
        </button>
      </div>
      <ul className="space-y-0.5">
        {focused.length === 0 && (
          <li className="px-3 py-2 text-[11px] text-ink-400 italic">ยังไม่ได้เลือก — กด "เลือก"</li>
        )}
        {focused.map(d => (
          <li key={d.id}>
            <button className="w-full flex items-center gap-2 px-3 py-1.5 hover:bg-ink-50 rounded-md text-left">
              <Avatar user={{ avatar: d.name.charAt(0), color: d.role === 'BT' ? '#2F5DE5' : '#10B981' }} size={22} />
              <div className="flex-1 min-w-0">
                <div className="text-xs text-ink-800 font-medium truncate flex items-center gap-1">
                  <span className="text-amber-500 text-[10px]">★</span>{d.name}
                </div>
                <div className="text-[9px] text-ink-400 num truncate">{d.pin} · {d.ppv.toLocaleString()}PV</div>
              </div>
            </button>
          </li>
        ))}
      </ul>

      <Modal open={picking} onClose={() => setPicking(false)} title="เลือก Focus 5 DL" size="md" footer={
        <div className="flex items-center justify-between">
          <span className="text-[11px] text-ink-500">เลือกได้สูงสุด 5 คน · ตอนนี้ {focusIds.length}/5</span>
          <Btn variant="brand" size="sm" onClick={() => setPicking(false)}>เสร็จสิ้น</Btn>
        </div>
      }>
        <div className="space-y-1.5 max-h-[400px] overflow-y-auto scroll-thin">
          {window.ABO_LIST.map(a => {
            const isFocus = focusIds.includes(a.id);
            const disabled = !isFocus && focusIds.length >= 5;
            return (
              <button key={a.id} onClick={() => toggle(a.id)} disabled={disabled}
                className={`w-full flex items-center gap-3 p-2.5 rounded-lg text-left transition-all ${
                  isFocus ? 'bg-amber-50 border border-amber-200 ring-1 ring-amber-200' :
                  disabled ? 'opacity-40' : 'hover:bg-ink-50 border border-transparent'
                }`}>
                <Avatar user={{ avatar: a.name.charAt(0), color: a.role === 'BT' ? '#2F5DE5' : '#10B981' }} size={32} />
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-ink-900 truncate flex items-center gap-1.5">
                    {a.name}
                    {a.role === 'BT' && <Pill color="#2F5DE5" tint="#EEF4FF" size="xs">BT</Pill>}
                  </div>
                  <div className="text-[11px] text-ink-500 num">{a.pin} · {a.ppv.toLocaleString()}PV · {a.downlines} DL</div>
                </div>
                <div className={`w-6 h-6 rounded-full flex items-center justify-center ${isFocus ? 'bg-amber-400 text-white' : 'border-2 border-ink-200'}`}>
                  {isFocus && <Icon name="check" className="w-3.5 h-3.5" strokeWidth={3} />}
                </div>
              </button>
            );
          })}
        </div>
      </Modal>
    </div>
  );
}

// Save defaults so Reset works
window.__DEFAULT_APPT_TYPES = window.APPT_TYPES.map(t => ({...t}));
window.__DEFAULT_LEAD_SOURCES = window.LEAD_SOURCES.map(s => ({...s}));

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