// Repairo — App shell: state machine + tweaks
const { useState, useEffect } = React;

const ACCENTS = [
  { id: 'charcoal', label: 'Charcoal', value: '#0F0F0E' },
  { id: 'terra',    label: 'Terrakotta', value: '#C5573A' },
  { id: 'forest',   label: 'Wald', value: '#3F5D3A' },
  { id: 'denim',    label: 'Denim', value: '#3A5A8C' },
];

const PROBLEM_OPTIONS = [
  { id: 'faucet', label: 'Wasserhahn' },
  { id: 'washer', label: 'Waschmaschine' },
  { id: 'switch', label: 'Lichtschalter' },
];

const SCREENS = ['home','camera','describe','analyzing','diagnosis','manual','steps','pros','pro-detail','sent'];

function App() {
  const [t, setTweak] = useTweaks(/*EDITMODE-BEGIN*/{
    "accent": "charcoal",
    "problem": "faucet"
  }/*EDITMODE-END*/);

  const editMode = typeof window !== 'undefined'
    && new URLSearchParams(window.location.search).get('edit') === '1';

  const accent = ACCENTS.find(a => a.id === t.accent)?.value || ACCENTS[0].value;
  const problem = PROBLEMS[t.problem] || PROBLEMS.faucet;

  const [screen, setScreen] = useState('home');
  const [transitionKey, setTransitionKey] = useState(0);
  const [activePro, setActivePro] = useState(HANDYMEN[0]);

  const go = (s) => {
    setScreen(s);
    setTransitionKey(k => k + 1);
  };

  const openPro = (p) => { setActivePro(p); go('pro-detail'); };
  const onSend = () => go('sent');

  let view;
  switch (screen) {
    case 'home':       view = <HomeScreen go={go} accent={accent} problem={problem} />; break;
    case 'camera':     view = <CameraScreen go={go} accent={accent} problem={problem} />; break;
    case 'describe':   view = <DescribeScreen go={go} accent={accent} problem={problem} />; break;
    case 'analyzing':  view = <AnalyzingScreen go={go} accent={accent} problem={problem} />; break;
    case 'diagnosis':  view = <DiagnosisScreen go={go} accent={accent} problem={problem} />; break;
    case 'manual':     view = <ManualScreen go={go} accent={accent} problem={problem} />; break;
    case 'steps':      view = <StepsScreen go={go} accent={accent} problem={problem} />; break;
    case 'pros':       view = <ProsScreen go={go} accent={accent} problem={problem} openPro={openPro} />; break;
    case 'pro-detail': view = <ProDetailScreen go={go} accent={accent} problem={problem} pro={activePro} onSend={onSend} />; break;
    case 'sent':       view = <SentScreen go={go} accent={accent} pro={activePro} />; break;
    default:           view = <HomeScreen go={go} accent={accent} problem={problem} />;
  }

  // Scale the device to fit the viewport
  const [scale, setScale] = useState(1);
  useEffect(() => {
    const fit = () => {
      const vh = window.innerHeight;
      const vw = window.innerWidth;
      const s = Math.min(1, (vh - 60) / 874, (vw - 40) / 402);
      setScale(s);
    };
    fit();
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, []);

  return (
    <div style={{
      minHeight: '100vh', background: '#E8E4D8',
      backgroundImage: 'radial-gradient(circle at 30% 20%, #EFEBDF 0%, #E2DECF 70%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '32px 16px', boxSizing: 'border-box',
      fontFamily: '"Instrument Sans", system-ui, sans-serif',
      overflow: 'hidden',
    }}>
      {/* Background editorial scaffold */}
      <div style={{
        position: 'fixed', top: 28, left: 32, color: 'rgba(15,15,14,0.45)',
        fontFamily: '"JetBrains Mono", monospace', fontSize: 11, letterSpacing: 2,
      }}>REPAIRO / v0.1 / DEMO</div>
      <div style={{
        position: 'fixed', top: 28, right: 32, color: 'rgba(15,15,14,0.45)',
        fontFamily: '"JetBrains Mono", monospace', fontSize: 11, letterSpacing: 2,
      }}>{String(SCREENS.indexOf(screen) + 1).padStart(2,'0')} / {String(SCREENS.length).padStart(2,'0')} · {screen.toUpperCase()}</div>
      <div style={{
        position: 'fixed', bottom: 24, left: 32, color: 'rgba(15,15,14,0.45)',
        fontFamily: '"Instrument Serif", serif', fontStyle: 'italic', fontSize: 14,
      }}>scan · diagnose · repair</div>

      <div style={{
        position: 'relative',
        width: 402 * scale, height: 874 * scale,
      }}>
        <div style={{
          position: 'absolute', top: 0, left: 0,
          width: 402, height: 874,
          transform: `scale(${scale})`,
          transformOrigin: 'top left',
        }}>
        <IOSDevice width={402} height={874}>
          <div key={transitionKey} style={{
            position: 'absolute', inset: 0, animation: 'rep-fade 0.32s ease-out',
          }}>
            {view}
          </div>
        </IOSDevice>
        </div>
      </div>

      {/* Tweaks — only visible with ?edit=1 in URL */}
      {editMode && (
        <TweaksPanel title="Tweaks" hint="Akzentfarbe & Beispiel-Problem">
          <TweakSection label="Akzentfarbe">
            <TweakColor
              label="Akzent"
              value={accent}
              onChange={(v) => {
                const a = ACCENTS.find(x => x.value === v);
                if (a) setTweak('accent', a.id);
              }}
              options={ACCENTS.map(a => a.value)}
            />
          </TweakSection>
          <TweakSection label="Beispiel-Problem">
            <TweakSelect
              label="Problem"
              value={t.problem}
              onChange={(v) => { setTweak('problem', v); go('home'); }}
              options={PROBLEM_OPTIONS.map(p => ({ value: p.id, label: p.label }))}
            />
            <div style={{ fontSize: 11, color: '#888', marginTop: 6, lineHeight: 1.4 }}>
              Wechselt Diagnose, Foto-Tint, Schritte und Sicherheitswarnung.
            </div>
          </TweakSection>
          <TweakSection label="Flow">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
              {SCREENS.map(s => (
                <button key={s} onClick={() => go(s)} style={{
                  padding: '6px 10px', borderRadius: 6,
                  border: '1px solid ' + (screen === s ? '#0F0F0E' : '#ddd'),
                  background: screen === s ? '#0F0F0E' : '#fff',
                  color: screen === s ? '#fff' : '#333',
                  fontSize: 11, cursor: 'pointer', fontFamily: 'inherit',
                }}>{s}</button>
              ))}
            </div>
          </TweakSection>
        </TweaksPanel>
      )}
    </div>
  );
}

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