
const { useState, useEffect, useCallback } = React;

const STORAGE_KEY = 'tl_profile_v1';
const API_BASE = 'https://transfer-lens.onrender.com';


function loadProfile() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY)); } catch { return null; }
}

function AppShell() {
  const [theme, setTheme] = useState(() => localStorage.getItem('tl_theme') || 'light');
  const [view, setView] = useState(() => {
    const p = loadProfile();
    return p?.setupDone ? 'app' : 'landing';
  });
  const [tab, setTab] = useState('plan');
  const [chatOpen, setChatOpen] = useState(false);
  const [profile, setProfile] = useState(() => loadProfile() || window.DEMO_PLAN);
  const [genError, setGenError] = useState(null);

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('tl_theme', theme);
  }, [theme]);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(profile));
  }, [profile]);

  const updateProfile = useCallback((patch) => {
    setProfile(prev => ({ ...prev, ...patch }));
  }, []);

  const handleStart = () => { setView('wizard'); };

  const handleWizardComplete = async (wizardState) => {
    setGenError(null);
    setView('generating');
    try {
      const majorIds = wizardState.selections.filter(s => s.major?.id).map(s => s.major.id);

      const res = await fetch(`${API_BASE}/api/generate-plan`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          major_ids: majorIds,
          transfer_term: wizardState.term,
          use_summer: wizardState.useSummer,
          summer_load: wizardState.summerLoad || 'light',
          ge_selections: wizardState.geSelections || {},
        }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const plan = await res.json();

      window.MOCK_COURSES = {};
      for (const [key, info] of Object.entries(plan.courses || {})) {
        window.MOCK_COURSES[key] = {
          title: info.title,
          units: info.units,
          difficulty: 'medium',
          available: 'FS',
        };
      }

      setProfile({
        cc: wizardState.cc,
        transferTerm: wizardState.term,
        useSummer: wizardState.useSummer,
        summerLoad: wizardState.summerLoad || 'light',
        selections: wizardState.selections.map(s => ({
          school: s.school,
          major: s.major?.label || 'Unknown Major',
        })),
        majorIds,
        geSelections: wizardState.geSelections || {},
        calgetcMode: wizardState.calgetcMode,
        honorsMode: false,
        setupDone: true,
        extraSems: [],
        hiddenSems: [],
        semesters: plan.semesters,
        courseStatuses: plan.course_statuses || {},
        courseGrades: plan.course_grades || {},
      });
      setView('app');
      setTab('plan');
    } catch (e) {
      console.error('Plan generation error:', e);
      setGenError('Something went wrong generating your plan. Please try again.');
    }
  };

  const handleReset = () => {
    localStorage.removeItem(STORAGE_KEY);
    setProfile(window.DEMO_PLAN);
    setGenError(null);
    setView('landing');
    setChatOpen(false);
  };

  const ThemeBtn = () => (
    <button className="theme-toggle" onClick={() => setTheme(t => t === 'dark' ? 'light' : 'dark')} aria-label="Toggle theme">
      {theme === 'dark'
        ? <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="3.5" stroke="currentColor" strokeWidth="1.5"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.42 1.42M11.53 11.53l1.42 1.42M3.05 12.95l1.42-1.42M11.53 4.47l1.42-1.42" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
        : <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M13.5 9.5A5.5 5.5 0 016.5 2.5a5.5 5.5 0 107 7z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/></svg>
      }
    </button>
  );

  if (view === 'landing') {
    return (
      <div className="app-root">
        <header className="app-header">
          <div className="app-header-inner app-header-full" style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center' }}>
            <div style={{ justifySelf: 'start' }}></div>
            <div className="app-logo"><span className="logo-transfer">Transfer</span><span className="logo-lens">Lens</span></div>
            <div style={{ justifySelf: 'end' }}><ThemeBtn /></div>
          </div>
        </header>
        <window.LandingPage onStart={handleStart} />
      </div>
    );
  }

  if (view === 'wizard') {
    return (
      <div className="app-root">
        <header className="app-header">
          <div className="app-header-inner app-header-full" style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center' }}>
            <div style={{ justifySelf: 'start' }}></div>
            <button className="app-logo app-logo-btn" onClick={() => setView('landing')}>
              <span className="logo-transfer">Transfer</span><span className="logo-lens">Lens</span>
            </button>
            <div style={{ justifySelf: 'end' }}><ThemeBtn /></div>
          </div>
        </header>
        <window.Wizard onComplete={handleWizardComplete} />
      </div>
    );
  }

  if (view === 'generating') {
    return (
      <div className="app-root">
        <header className="app-header">
          <div className="app-header-inner app-header-full" style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center' }}>
            <div style={{ justifySelf: 'start' }}></div>
            <div className="app-logo"><span className="logo-transfer">Transfer</span><span className="logo-lens">Lens</span></div>
            <div style={{ justifySelf: 'end' }}></div>
          </div>
        </header>
        <div className="wizard-overlay">
          <div className="wizard-inner" style={{ textAlign: 'center' }}>
            {genError ? (
              <>
                <div className="wiz-q" style={{ color: 'var(--red)' }}>Something went wrong</div>
                <div className="wiz-hint">{genError}</div>
                <button className="wiz-generate-btn" style={{ marginTop: 32 }} onClick={() => { setGenError(null); setView('wizard'); }}>
                  ← Back to Wizard
                </button>
              </>
            ) : (
              <>
                <div className="wiz-q">Building your plan…</div>
                <div className="wiz-hint">Fetching articulation agreements and scheduling your courses.</div>
                <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--accent)', margin: '32px auto 0', animation: 'pulse 1.2s ease-in-out infinite' }} />
              </>
            )}
          </div>
        </div>
      </div>
    );
  }

  const tabs = [
    { id: 'plan',     label: 'Plan' },
    { id: 'transfer', label: 'Transfer' },
    { id: 'calgetc',  label: 'Cal-GETC' },
  ];

  return (
    <div className="app-root">
      <header className="app-header">
        <div className="app-header-inner app-header-full" style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center' }}>
          <button className="app-logo app-logo-btn" onClick={handleReset} style={{ justifySelf: 'start' }}>
            <span className="logo-transfer">Transfer</span><span className="logo-lens">Lens</span>
          </button>
          <nav className="app-tabs">
            {tabs.map(t => (
              <button key={t.id} className={`app-tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>
                {t.label}
              </button>
            ))}
          </nav>
          <div className="app-header-right" style={{ justifySelf: 'end' }}>
            <ThemeBtn />
          </div>
        </div>
      </header>

      <main className={`app-main ${tab === 'plan' ? 'app-main-wide' : ''}`}>
        <div className="tab-content fade-in" key={tab}>
          {tab === 'plan'     && <window.PlanView     profile={profile} onUpdateProfile={updateProfile} onReset={handleReset} />}
          {tab === 'transfer' && <window.TransferView  profile={profile} onUpdateProfile={updateProfile} />}
          {tab === 'calgetc'  && <window.CalGETCView   profile={profile} onUpdateProfile={updateProfile} />}
        </div>
      </main>

      <button className={`chat-fab ${chatOpen ? 'chat-fab-hidden' : ''}`} onClick={() => setChatOpen(true)} aria-label="Open advisor chat">
        <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><path d="M4 4h14a2 2 0 012 2v8a2 2 0 01-2 2H8l-4 4V6a2 2 0 012-2z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>
        <span className="chat-fab-label">Ask Advisor</span>
      </button>

      <window.ChatPanel open={chatOpen} onClose={() => setChatOpen(false)} profile={profile} />
    </div>
  );
}

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