// Main App with routing + tweaks
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#6CB274",
  "displayFont": "poppins",
  "uiFont": "poppins",
  "bodyWeight": 500
}/*EDITMODE-END*/;

// Curated accent options — toned-down naturals + a louder original orange so the user can compare.
const ACCENT_OPTIONS = [
  "#6CB274", // sage green — current
  "#5B8F87", // muted teal
  "#1E3A8A", // navy
  "#9C6CC7", // soft violet
  "#C5594E", // brick red
  "#FF5C39", // original spicy orange
  "#1A1A1A", // monochrome
];

const UI_FONT_OPTIONS = [
  { id: 'poppins', label: 'Poppins', stack: `'Poppins', system-ui, sans-serif` },
  { id: 'inter',   label: 'Inter',   stack: `'Inter', system-ui, sans-serif` },
];

const DISPLAY_FONT_OPTIONS = [
  { id: 'instrument', label: 'Instrument Serif', stack: `'Instrument Serif', Georgia, serif` },
  { id: 'poppins',    label: 'Poppins',          stack: `'Poppins', system-ui, sans-serif` },
];

function hexToRgb(hex) {
  const h = hex.replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c+c).join('') : h, 16);
  return `${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}`;
}
function darken(hex, amt = 0.15) {
  const [r, g, b] = hexToRgb(hex).split(',').map(s => parseInt(s.trim()));
  const dr = Math.max(0, Math.floor(r * (1 - amt)));
  const dg = Math.max(0, Math.floor(g * (1 - amt)));
  const db = Math.max(0, Math.floor(b * (1 - amt)));
  return `#${[dr, dg, db].map(x => x.toString(16).padStart(2,'0')).join('')}`;
}

// Catches render-time crashes so a bug in one screen doesn't white-screen the app.
class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { err: null }; }
  static getDerivedStateFromError(err) { return { err }; }
  componentDidCatch(err, info) { console.error('App error:', err, info); }
  render() {
    if (this.state.err) {
      return (
        <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, textAlign: 'center' }}>
          <div style={{ maxWidth: 420 }}>
            <img src="assets/brand/icon.png" alt="Resumerush" style={{ width: 64, height: 64, borderRadius: 18, display: 'block', margin: '0 auto 24px' }}/>
            <h2 className="t-h2" style={{ margin: 0 }}>Something broke.</h2>
            <p className="t-body secondary" style={{ marginTop: 8, marginBottom: 24 }}>
              An unexpected error occurred. Reloading usually fixes it.
            </p>
            <Btn variant="primary" onClick={() => window.location.reload()}>Reload</Btn>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

function App() {
  const [route, setRoute] = useState('landing');
  const [routeParams, setRouteParams] = useState({});
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Real app state shared across screens.
  const [surveyData, setSurveyData] = useState(null);          // payload sent to /api/generate
  const [resume, setResume] = useState(null);                  // generated/loaded resume object
  const [selectedResumeId, setSelectedResumeId] = useState(null); // id of the open resume (for saving)
  const [user, setUser] = useState(null);                      // Supabase user (null when signed out)
  const routeRef = useRef(route);
  routeRef.current = route;

  // Subscribe to Supabase auth changes (no-op when auth is mocked). A signed-in
  // user is sent straight to their dashboard instead of the marketing landing —
  // this also covers the post-Google-OAuth reload, which lands on 'landing'.
  useEffect(() => {
    if (!window.RR?.auth) return;
    const onUser = (u) => {
      setUser(u);
      if (u && routeRef.current === 'landing') go('dashboard');
    };
    window.RR.auth.getUser().then(u => u && onUser(u));
    const off = window.RR.auth.onChange(onUser);
    return off;
  }, []);

  // Apply tweaks to :root
  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty('--accent-primary', t.accent);
    root.style.setProperty('--accent-primary-hover', darken(t.accent, 0.12));
    root.style.setProperty('--accent-rgb', hexToRgb(t.accent));

    const ui = UI_FONT_OPTIONS.find(f => f.id === t.uiFont)?.stack || UI_FONT_OPTIONS[0].stack;
    const display = DISPLAY_FONT_OPTIONS.find(f => f.id === t.displayFont)?.stack || DISPLAY_FONT_OPTIONS[0].stack;
    root.style.setProperty('--font-ui', ui);
    root.style.setProperty('--font-display', display);
    document.body.style.fontWeight = t.bodyWeight;
    document.body.dataset.displayFont = t.displayFont;
    document.body.dataset.uiFont = t.uiFont;
  }, [t.accent, t.uiFont, t.displayFont, t.bodyWeight]);

  const go = (r, params = {}) => {
    // Starting a brand-new resume — clear any open resume/survey state.
    if (r === 'welcome') { setResume(null); setSelectedResumeId(null); setSurveyData(null); }
    setRouteParams(params);
    setRoute(r);
    const el = document.getElementById('landing-scroll');
    if (el) el.scrollTop = 0;
    window.scrollTo(0, 0);
  };

  const routes = [
    { id: 'landing', label: 'Landing' },
    { id: 'signup', label: 'Sign up' },
    { id: 'login', label: 'Log in' },
    { id: 'welcome', label: 'Welcome' },
    { id: 'survey', label: 'Survey' },
    { id: 'generating', label: 'Generating' },
    { id: 'preview', label: 'Preview' },
    { id: 'export', label: 'Export' },
    { id: 'beautify', label: 'Beautify' },
    { id: 'dashboard', label: 'Dashboard' },
  ];

  const openId = routeParams.resumeId || selectedResumeId;

  return (
    <div className="app" data-screen-label={routes.find(r=>r.id === route)?.label}>
      <ErrorBoundary key={route}>
        {route === 'landing' && <LandingScreen go={go}/>}
        {route === 'signup' && <AuthScreen go={go} mode="signup" onAuth={setUser}/>}
        {route === 'login' && <AuthScreen go={go} mode="login" onAuth={setUser}/>}
        {route === 'forgot' && <ForgotScreen go={go}/>}
        {route === 'welcome' && <WelcomeScreen go={go} user={user}/>}
        {route === 'survey' && <SurveyScreen go={go} onComplete={setSurveyData} resume={routeParams.resume}/>}
        {route === 'generating' && <GeneratingScreen go={go} surveyData={surveyData} setResume={setResume} setResumeId={setSelectedResumeId}/>}
        {route === 'preview' && <PreviewScreen go={go} resume={resume} setResume={setResume} surveyData={surveyData} resumeId={openId} setResumeId={setSelectedResumeId} user={user}/>}
        {route === 'export' && <ExportScreen go={go} resume={resume} user={user}/>}
        {route === 'beautify' && <BeautifyScreen go={go} resume={resume}/>}
        {route === 'dashboard' && <DashboardScreen go={go} user={user}/>}
      </ErrorBoundary>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent color">
          <TweakColor label="Accent" value={t.accent} options={ACCENT_OPTIONS} onChange={(v)=>setTweak('accent', v)}/>
        </TweakSection>
        <TweakSection label="Type">
          <TweakRadio label="UI font" value={t.uiFont}
            options={UI_FONT_OPTIONS.map(f => f.id)}
            onChange={(v)=>setTweak('uiFont', v)}/>
          <TweakRadio label="Display font" value={t.displayFont}
            options={DISPLAY_FONT_OPTIONS.map(f => f.id)}
            onChange={(v)=>setTweak('displayFont', v)}/>
          <TweakRadio label="Body weight" value={t.bodyWeight}
            options={[400, 500, 600]}
            onChange={(v)=>setTweak('bodyWeight', v)}/>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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