// App shell — state, routing, side-by-side stage
const T = window.TB;

function App() {
  const [screen, setScreen] = React.useState('home');
  const [answers, setAnswers] = React.useState({
    living_in_germany: undefined,
    status: undefined,
    income_types: [],
    filed_before: undefined,
    advisor: undefined,
    help_with: [],
    urgency: undefined,
    save: undefined,
  });

  // Tweakable defaults — view mode
  const [t, setTweak] = window.useTweaks(/*EDITMODE-BEGIN*/{
    "view": "both",
    "showProgressDots": true,
    "accent": "#3AD29F"
  }/*EDITMODE-END*/);

  const go = (s) => setScreen(s);

  // Reset answers when navigating home from dashboard
  const goHome = () => { setScreen('home'); };

  // Quick jump for demo
  const jumpTo = (s) => {
    if (s === 'result' || s === 'register' || s === 'dashboard') {
      // pre-fill demo answers if user is jumping
      if (!answers.income_types || answers.income_types.length === 0) {
        setAnswers({
          living_in_germany: 'yes',
          status: 'employee',
          income_types: ['salary', 'rsu', 'foreign', 'crypto'],
          filed_before: 'never',
          advisor: 'none',
          help_with: ['first', 'refund', 'match'],
          urgency: 'planning',
          save: 'save',
        });
      }
    }
    setScreen(s);
  };

  const view = t.view;
  const showDesktop = view === 'both' || view === 'desktop';
  const showMobile = view === 'both' || view === 'mobile';

  return (
    <div style={{
      width: '100vw', height: '100vh',
      background: `radial-gradient(circle at 30% 20%, #0F2348, ${T.inkDeep})`,
      overflow: 'hidden', position: 'relative',
      fontFamily: T.font,
    }}>
      {/* Top bar — demo controls */}
      <DemoBar screen={screen} jumpTo={jumpTo}/>

      {/* Stage */}
      <div style={{
        position: 'absolute', top: 56, left: 0, right: 0, bottom: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        gap: 28, padding: '24px 32px',
        overflow: 'hidden',
      }}>
        {showDesktop && (
          <DesktopFrame screen={screen} solo={!showMobile}>
            <ScreenRouter screen={screen} go={go} answers={answers} setAnswers={setAnswers} mobile={false}/>
          </DesktopFrame>
        )}
        {showMobile && (
          <MobileFrame solo={!showDesktop}>
            <ScreenRouter screen={screen} go={go} answers={answers} setAnswers={setAnswers} mobile={true}/>
          </MobileFrame>
        )}
      </div>

      {/* Tweaks panel */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="View">
          <window.TweakRadio
            label="Showing" value={t.view}
            options={['both', 'desktop', 'mobile']}
            onChange={(v) => setTweak('view', v)}
          />
        </window.TweakSection>
        <window.TweakSection label="Quick demo">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              ['home', '01 · Home'],
              ['assessment', '02 · Tax assessment'],
              ['result', '03 · Preliminary profile'],
              ['register', '04 · Create account'],
              ['dashboard', '05 · Dashboard'],
            ].map(([k, l]) => (
              <button key={k} onClick={() => jumpTo(k)} style={{
                padding: '9px 12px', borderRadius: 9,
                background: screen === k ? T.ink : '#fff',
                color: screen === k ? '#fff' : T.ink,
                border: `1px solid ${screen === k ? T.ink : T.border}`,
                fontFamily: T.font, fontSize: 13, fontWeight: 500,
                cursor: 'pointer', textAlign: 'left',
              }}>{l}</button>
            ))}
          </div>
        </window.TweakSection>
      </window.TweaksPanel>
    </div>
  );
}

// ─── Demo Bar (top, dark) ─────────────────────────────────
function DemoBar({ screen, jumpTo }) {
  const flow = [
    { k: 'home', l: 'Home' },
    { k: 'assessment', l: 'Assessment' },
    { k: 'result', l: 'Profile' },
    { k: 'register', l: 'Register' },
    { k: 'dashboard', l: 'Dashboard' },
  ];
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0, height: 56,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '0 24px',
      background: 'rgba(6,18,42,0.7)',
      backdropFilter: 'blur(12px)',
      borderBottom: '1px solid rgba(255,255,255,0.08)',
      zIndex: 100,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, color: '#fff' }}>
        <Logo size={18} color="#fff" accent={T.mint}/>
        <span style={{
          fontFamily: T.mono, fontSize: 11, color: 'rgba(255,255,255,0.5)',
          textTransform: 'uppercase', letterSpacing: 0.8,
          paddingLeft: 14, marginLeft: 4,
          borderLeft: '1px solid rgba(255,255,255,0.15)',
        }}>Interactive prototype · v1.0</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, background: 'rgba(255,255,255,0.06)', borderRadius: 999, padding: 4 }}>
        {flow.map((s, i) => (
          <React.Fragment key={s.k}>
            <button onClick={() => jumpTo(s.k)} style={{
              padding: '6px 13px', borderRadius: 999,
              background: screen === s.k ? T.mint : 'transparent',
              color: screen === s.k ? T.ink : 'rgba(255,255,255,0.75)',
              border: 0, cursor: 'pointer',
              fontFamily: T.font, fontSize: 12, fontWeight: screen === s.k ? 600 : 500,
            }}>
              <span style={{ fontFamily: T.mono, opacity: 0.6, marginRight: 6 }}>0{i+1}</span>
              {s.l}
            </button>
            {i < flow.length - 1 && (
              <div style={{ width: 12, color: 'rgba(255,255,255,0.2)', textAlign: 'center', fontSize: 10 }}>›</div>
            )}
          </React.Fragment>
        ))}
      </div>
      <a href="/variations" style={{
        fontFamily: T.font, fontSize: 12, color: 'rgba(255,255,255,0.75)',
        textDecoration: 'none', padding: '7px 12px', borderRadius: 8,
        border: '1px solid rgba(255,255,255,0.15)',
      }}>See variations →</a>
    </div>
  );
}

// ─── Desktop frame (browser chrome) ─────────────────────
function DesktopFrame({ children, screen, solo }) {
  // Compute scale to fit the available space
  const ref = React.useRef(null);
  const [scale, setScale] = React.useState(1);
  const [size, setSize] = React.useState({ w: 1280, h: 800 });

  React.useLayoutEffect(() => {
    function compute() {
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const baseW = 1280, baseH = 800;
      const s = Math.min(r.width / baseW, r.height / baseH, 1);
      setScale(s);
    }
    compute();
    const ro = new ResizeObserver(compute);
    if (ref.current) ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);

  return (
    <div ref={ref} style={{
      flex: solo ? '1 1 0' : '1.2 1 0', height: '100%',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      minWidth: 0,
    }}>
      <div style={{
        width: 1280, height: 800,
        transform: `scale(${scale})`, transformOrigin: 'center center',
        flexShrink: 0,
      }}>
        <window.ChromeWindow
          width={1280} height={800}
          url={`tax-bridge.de${screen === 'home' ? '' : '/' + screen}`}
          tabs={[{ title: 'Tax Bridge — ' + screen[0].toUpperCase() + screen.slice(1) }]}
        >
          <div style={{ height: '100%', overflow: 'auto' }}>
            {children}
          </div>
        </window.ChromeWindow>
      </div>
    </div>
  );
}

// ─── Mobile frame (custom slim bezel) ───────────────────
function MobileFrame({ children, solo }) {
  const ref = React.useRef(null);
  const [scale, setScale] = React.useState(1);

  React.useLayoutEffect(() => {
    function compute() {
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const baseW = 380, baseH = 800;
      const s = Math.min(r.width / baseW, r.height / baseH, 1);
      setScale(s);
    }
    compute();
    const ro = new ResizeObserver(compute);
    if (ref.current) ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);

  return (
    <div ref={ref} style={{
      flex: solo ? '1 1 0' : '0 0 auto', width: solo ? '100%' : 460, height: '100%',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      minWidth: 0,
    }}>
      <div style={{
        width: 380, height: 800,
        transform: `scale(${scale})`, transformOrigin: 'center center',
        flexShrink: 0,
        position: 'relative',
        background: '#0A0A0E', borderRadius: 48,
        padding: 12,
        boxShadow: '0 30px 80px rgba(0,0,0,0.4), inset 0 0 0 2px rgba(255,255,255,0.05)',
      }}>
        {/* notch */}
        <div style={{
          position: 'absolute', top: 14, left: '50%', transform: 'translateX(-50%)',
          width: 110, height: 30, borderRadius: 999, background: '#0A0A0E',
          zIndex: 30,
        }}/>
        <div style={{
          width: '100%', height: '100%', borderRadius: 36,
          background: '#fff', overflow: 'hidden',
          position: 'relative',
        }}>
          {/* status bar */}
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0, height: 44,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '0 28px', paddingTop: 14, zIndex: 20,
            fontFamily: '-apple-system, "SF Pro", system-ui',
            fontSize: 14, fontWeight: 600, color: T.ink,
          }}>
            <span>9:41</span>
            <div style={{ display: 'flex', gap: 4 }}>
              <svg width="16" height="10" viewBox="0 0 16 10"><path d="M1 8h2v1H1zM5 6h2v3H5zM9 3h2v6H9zM13 0h2v9h-2z" fill={T.ink}/></svg>
              <svg width="22" height="10" viewBox="0 0 22 10"><rect x="1" y="2" width="18" height="6" rx="1.5" stroke={T.ink} strokeWidth="0.8" fill="none"/><rect x="2" y="3" width="14" height="4" rx="0.5" fill={T.ink}/></svg>
            </div>
          </div>
          <div style={{ height: '100%', paddingTop: 44, overflow: 'auto', boxSizing: 'border-box' }}>
            {children}
          </div>
          {/* home indicator */}
          <div style={{
            position: 'absolute', bottom: 8, left: '50%', transform: 'translateX(-50%)',
            width: 130, height: 4, borderRadius: 999, background: 'rgba(0,0,0,0.3)', zIndex: 30,
          }}/>
        </div>
      </div>
    </div>
  );
}

// ─── Screen router ─────────────────────────────────
function ScreenRouter({ screen, go, answers, setAnswers, mobile }) {
  if (screen === 'home') return <window.HomeScreen go={go} mobile={mobile}/>;
  if (screen === 'assessment') return <window.AssessmentScreen go={go} answers={answers} setAnswers={setAnswers} mobile={mobile}/>;
  if (screen === 'result') return <window.ResultScreen go={go} answers={answers} mobile={mobile}/>;
  if (screen === 'register') return <window.RegisterScreen go={go} mobile={mobile}/>;
  if (screen === 'dashboard') return <window.DashboardScreen go={go} answers={answers} mobile={mobile}/>;
  return null;
}

window.App = App;
