// Ledger SNA login — main flow controller
const { useState, useEffect, useCallback, useRef } = React;

// ─────────────────────────────────────────────
// Palettes (curated for fintech)
// ─────────────────────────────────────────────
const PALETTES = {
  indigo: { primary: '#4f46e5', name: 'Indigo' },
  emerald: { primary: '#0f8a5f', name: 'Emerald' },
  graphite: { primary: '#26272f', name: 'Graphite' },
  amber: { primary: '#b8500d', name: 'Amber' }
};

// Step orders by scenario — purely SNA, no OTP path
const STEPS_DATA_ON = ['phone', 'loader', 'success'];
const STEPS_DATA_OFF = ['phone', 'enableData', 'loader', 'success'];
const STEPS_WRONG_SIM = ['phone', 'switchSim', 'loader', 'success'];

// ─────────────────────────────────────────────
// Step rail (annotated flow on the right)
// ─────────────────────────────────────────────
const StepRail = ({ current, onJump, scenario, onScenarioChange, onReplay, autoplay, onAutoplayChange, currentSteps }) => {
  const labels = {
    phone: { num: '01', title: 'Mobile number', desc: 'User enters phone. SIM info detected from device.' },
    enableData: { num: '02', title: 'Enable mobile data', desc: 'Data is off — prompt user to switch on so carrier can verify.' },
    switchSim: { num: '02', title: 'Switch data SIM', desc: 'Data is on SIM 1 but the number belongs to SIM 2 - ask user to switch.' },
    loader: { num: '—', title: 'Operator handshake', desc: 'Background: app pings carrier endpoint, verifies SIM silently.' },
    success: { num: '—', title: 'Signed in', desc: 'Carrier confirmed match. Session minted in under 2 seconds.' }
  };
  // Renumber dynamically
  currentSteps.forEach((s, i) => {labels[s] = { ...labels[s], num: String(i + 1).padStart(2, '0') };});

  return (
    <div className="rail">
      <div>
        <div style={{
          fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5,
          letterSpacing: 1.4, textTransform: 'uppercase', color: '#8b8e97'
        }}>
          Flow · Android
        </div>
        <h2 style={{
          fontFamily: "'DM Sans', system-ui",
          fontSize: 22, fontWeight: 600, letterSpacing: -0.5,
          margin: '6px 0 6px', color: '#0c0d12'
        }}>
          Silent Network Auth
        </h2>
        <p style={{ fontSize: 13, color: '#5a5d67', margin: 0, lineHeight: 1.5 }}>User authenticates by SIM only - no OTP, no password. The handset briefly uses mobile data so the carrier can verify the number.


        </p>
      </div>

      {/* steps */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {currentSteps.map((s, i) => {
          const isCurrent = s === current;
          const isPast = currentSteps.indexOf(current) > i;
          const lbl = labels[s];
          return (
            <button key={s} onClick={() => onJump(s)} style={{
              display: 'flex', gap: 14, padding: '12px 8px', textAlign: 'left',
              border: 'none', background: isCurrent ? 'rgba(79,70,229,0.06)' : 'transparent',
              borderRadius: 10, cursor: 'pointer', alignItems: 'flex-start',
              transition: 'background .2s ease'
            }}>
              <div style={{
                position: 'relative', display: 'flex', flexDirection: 'column',
                alignItems: 'center', flexShrink: 0, paddingTop: 2
              }}>
                <div style={{
                  width: 20, height: 20, borderRadius: '50%',
                  background: isCurrent ? '#4f46e5' : isPast ? '#4f46e5' : '#fff',
                  border: `1.5px solid ${isCurrent || isPast ? '#4f46e5' : '#d4d0c5'}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}>
                  {isPast ?
                  <svg width="10" height="10" viewBox="0 0 10 10">
                      <path d="M2 5 L4 7 L8 3" stroke="#fff" strokeWidth="1.6" fill="none" strokeLinecap="round" />
                    </svg> :
                  isCurrent ?
                  <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#fff' }} /> :
                  null}
                </div>
                {i < currentSteps.length - 1 &&
                <div style={{
                  width: 1.5, flex: 1, minHeight: 28,
                  background: isPast ? '#4f46e5' : '#dcd8cf',
                  marginTop: 4
                }} />
                }
              </div>
              <div style={{ flex: 1, paddingBottom: 8 }}>
                <div style={{
                  fontFamily: "'JetBrains Mono', monospace", fontSize: 10,
                  color: '#8b8e97', letterSpacing: 0.5, textTransform: 'uppercase'
                }}>{lbl.num}</div>
                <div style={{
                  fontFamily: "'DM Sans', system-ui", fontSize: 14,
                  fontWeight: 600, color: '#0c0d12', marginTop: 2
                }}>{lbl.title}</div>
                <div style={{
                  fontSize: 12, color: '#5a5d67', marginTop: 3, lineHeight: 1.4
                }}>{lbl.desc}</div>
              </div>
            </button>);

        })}
      </div>

      {/* scenario toggle */}
      <div style={{
        padding: 12, background: 'rgba(255,255,255,0.7)',
        borderRadius: 12, border: '1px solid rgba(0,0,0,0.05)'
      }}>
        <div style={{
          fontSize: 11, fontWeight: 500, color: '#8b8e97',
          letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 8
        }}>
          Starting condition
        </div>
        <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
          {[
          { id: 'dataOn', label: 'Data ON' },
          { id: 'dataOff', label: 'Data OFF' },
          { id: 'wrongSim', label: 'Dual SIM' }].
          map((o) =>
          <button key={o.id} onClick={() => onScenarioChange(o.id)} style={{
            flex: 1, padding: '8px 10px', borderRadius: 8,
            border: `1px solid ${scenario === o.id ? '#4f46e5' : '#dcd8cf'}`,
            background: scenario === o.id ? '#4f46e5' : '#fff',
            color: scenario === o.id ? '#fff' : '#0c0d12',
            fontFamily: "'DM Sans', system-ui", fontSize: 12, fontWeight: 600,
            cursor: 'pointer', transition: 'all .15s ease'
          }}>
              {o.label}
            </button>
          )}
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={onReplay} style={{
            flex: 1, padding: '8px 10px', borderRadius: 8,
            border: '1px solid #dcd8cf', background: '#fff', color: '#0c0d12',
            fontFamily: "'DM Sans', system-ui", fontSize: 12, fontWeight: 500,
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6
          }}>
            <svg width="11" height="11" viewBox="0 0 11 11" fill="none">
              <path d="M1 5.5 a4.5 4.5 0 1 0 1.3 -3.2 M1 0.5 V2.3 H2.8"
              stroke="#0c0d12" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" fill="none" />
            </svg>
            Replay
          </button>
          <button onClick={() => onAutoplayChange(!autoplay)} style={{
            flex: 1, padding: '8px 10px', borderRadius: 8,
            border: '1px solid #dcd8cf',
            background: autoplay ? '#0c0d12' : '#fff',
            color: autoplay ? '#fff' : '#0c0d12',
            fontFamily: "'DM Sans', system-ui", fontSize: 12, fontWeight: 500,
            cursor: 'pointer'
          }}>
            {autoplay ? '⏸ Pause autoplay' : '▶ Autoplay'}
          </button>
        </div>
      </div>
    </div>);

};

// ─────────────────────────────────────────────
// Main app
// ─────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "indigo",
  "dark": false,
  "loader": "pulse",
  "showFrame": true
} /*EDITMODE-END*/;

const App = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [step, setStep] = useState('phone');
  const [scenario, setScenario] = useState('dataOn'); // dataOn | dataOff | wrongSim
  const [phone, setPhone] = useState('');
  const [loaderStep, setLoaderStep] = useState(0);
  const [dataOn, setDataOn] = useState(true);
  const [dataSim, setDataSim] = useState(1); // which SIM has data
  const [autoplay, setAutoplay] = useState(true);
  const typingRef = useRef(null);
  const flowRef = useRef(null);

  const palette = PALETTES[t.palette] || PALETTES.indigo;
  const theme = { primary: palette.primary, dark: t.dark };
  const currentSteps = scenario === 'dataOff' ? STEPS_DATA_OFF :
  scenario === 'wrongSim' ? STEPS_WRONG_SIM :
  STEPS_DATA_ON;

  // Reset dataOn / dataSim when scenario changes
  useEffect(() => {
    setDataOn(scenario !== 'dataOff');
    setDataSim(scenario === 'wrongSim' ? 1 : 2); // wrongSim starts on SIM 1, number is SIM 2 (Jio)
  }, [scenario]);

  // ── replay ──
  const replay = useCallback(() => {
    clearTimeout(typingRef.current);
    clearTimeout(flowRef.current);
    setStep('phone');
    setPhone('');
    setLoaderStep(0);
    setDataOn(scenario === 'dataOn');
  }, [scenario]);

  // Auto-advance after phone is filled (hint picks it; user typing also works)
  useEffect(() => {
    if (!autoplay) return;
    if (step !== 'phone') return;
    if (phone.length < 10) return;
    flowRef.current = setTimeout(() => {
      if (scenario === 'dataOff') {
        setStep('enableData');
      } else if (scenario === 'wrongSim') {
        setStep('switchSim');
      } else {
        setLoaderStep(0);
        setStep('loader');
      }
    }, 900);
    return () => clearTimeout(flowRef.current);
  }, [phone, step, autoplay, scenario]);

  // On enableData: after a beat, simulate user flipping the toggle on, then continue
  useEffect(() => {
    if (!autoplay) return;
    if (step !== 'enableData') return;
    const t1 = setTimeout(() => setDataOn(true), 2000);
    const t2 = setTimeout(() => {
      setLoaderStep(0);
      setStep('loader');
    }, 3300);
    return () => {clearTimeout(t1);clearTimeout(t2);};
  }, [step, autoplay]);

  // On switchSim: simulate user switching the data SIM from 1 → 2, then continue
  useEffect(() => {
    if (!autoplay) return;
    if (step !== 'switchSim') return;
    const t1 = setTimeout(() => setDataSim(2), 2000);
    const t2 = setTimeout(() => {
      setLoaderStep(0);
      setStep('loader');
    }, 3300);
    return () => {clearTimeout(t1);clearTimeout(t2);};
  }, [step, autoplay]);

  // Loader: progress steps then advance to success
  useEffect(() => {
    if (step !== 'loader') return;
    setLoaderStep(0);
    const t1 = setTimeout(() => setLoaderStep(1), 1200);
    const t2 = setTimeout(() => setLoaderStep(2), 2400);
    const t3 = setTimeout(() => {
      if (autoplay) setStep('success');else
      setLoaderStep(2);
    }, 3600);
    return () => {clearTimeout(t1);clearTimeout(t2);clearTimeout(t3);};
  }, [step, autoplay]);

  // Loop after success in autoplay
  useEffect(() => {
    if (!autoplay) return;
    if (step !== 'success') return;
    flowRef.current = setTimeout(replay, 5500);
    return () => clearTimeout(flowRef.current);
  }, [step, autoplay, replay]);

  const handlePhoneContinue = () => {
    setAutoplay(false);
    if (scenario === 'dataOff' && !dataOn) {
      setStep('enableData');
    } else if (scenario === 'wrongSim' && dataSim === 1) {
      setStep('switchSim');
    } else {
      setLoaderStep(0);
      setStep('loader');
    }
  };

  const handleEnableDataContinue = () => {
    setAutoplay(false);
    setLoaderStep(0);
    setStep('loader');
  };

  const handleSwitchSimContinue = () => {
    setAutoplay(false);
    setLoaderStep(0);
    setStep('loader');
  };

  const handleSwitchSim = () => {
    setDataSim((s) => s === 1 ? 2 : 1);
  };

  const handleToggleData = () => {
    setDataOn((d) => !d);
  };

  const handleJump = (s) => {
    setAutoplay(false);
    if (s === 'phone') setPhone('');
    if (s === 'enableData') {setDataOn(false);}
    if (s === 'switchSim') {setDataSim(1);}
    if (s === 'loader' || s === 'success') {setDataOn(true);setDataSim(2);setLoaderStep(0);}
    if (!phone && s !== 'phone') setPhone('9876543210');
    setStep(s);
  };

  const handleScenarioChange = (id) => {
    setScenario(id);
    setStep('phone');
    setPhone('');
    setLoaderStep(0);
    setAutoplay(true);
  };

  const renderScreen = () => {
    switch (step) {
      case 'phone':
        return <PhoneInputScreen theme={theme} phone={phone} onPhoneChange={setPhone} onContinue={handlePhoneContinue} focusKey={phone.length} autoplay={autoplay} />;
      case 'enableData':
        return <EnableDataScreen theme={theme} phone={phone || '9876543210'} dataOn={dataOn} onToggleData={handleToggleData} onContinue={handleEnableDataContinue} />;
      case 'switchSim':
        return <SwitchSimScreen theme={theme} phone={phone || '9876543210'} dataSim={dataSim} onSwitchSim={handleSwitchSim} onContinue={handleSwitchSimContinue} />;
      case 'loader':
        return <LoaderScreen theme={theme} step={loaderStep} variant={t.loader} />;
      case 'success':
        return <SuccessScreen theme={theme} phone={phone || '9876543210'} />;
      default:
        return null;
    }
  };

  return (
    <div className="stage" data-screen-label="SNA Login Flow">
      <div className="phone-col">
        {t.showFrame ?
        <PhoneFrame dark={t.dark}>
            <div key={step} className="screen-enter screen-enter-active" style={{ height: '100%' }}>
              {renderScreen()}
            </div>
          </PhoneFrame> :

        <div style={{
          width: 392, height: 760, borderRadius: 28, overflow: 'hidden',
          boxShadow: '0 30px 80px -20px rgba(20,22,30,0.25)',
          background: t.dark ? '#0e0f15' : '#fff'
        }}>
            <div key={step} className="screen-enter screen-enter-active" style={{ height: '100%' }}>
              {renderScreen()}
            </div>
          </div>
        }
      </div>
      <StepRail
        current={step}
        currentSteps={currentSteps}
        onJump={handleJump}
        scenario={scenario}
        onScenarioChange={handleScenarioChange}
        onReplay={() => {setAutoplay(true);replay();}}
        autoplay={autoplay}
        onAutoplayChange={setAutoplay} />
      

      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand" />
        <TweakColor
          label="Primary"
          value={palette.primary}
          options={Object.values(PALETTES).map((v) => v.primary)}
          onChange={(hex) => {
            const key = Object.keys(PALETTES).find((k) => PALETTES[k].primary === hex) || 'indigo';
            setTweak('palette', key);
          }} />
        
        <TweakSection label="Theme" />
        <TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak('dark', v)} />
        <TweakToggle label="Device frame" value={t.showFrame} onChange={(v) => setTweak('showFrame', v)} />
        <TweakSection label="Loader visual" />
        <TweakRadio
          label="Style"
          value={t.loader}
          options={['pulse', 'spinner', 'wave']}
          onChange={(v) => setTweak('loader', v)} />
        
      </TweaksPanel>
    </div>);

};

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