// Login with Vi — main flow controller for the OTPless pitch.
//
// Architecture: the partner app (Bazaar) renders as the base layer for the consent flow.
// The Vi SDK sheet (ViSdkSheet) overlays it for the entire flow:
//   verifying → consent → (dpdp) → done → dismiss
// After dismiss, Bazaar home (signed-in) renders. The Vi manage-consent screen is
// the only step rendered in the Vi app's own surface — it's a separate context.

const { useState, useEffect, useCallback, useRef } = React;

// ──────────────────────────────────────────────
// Step definitions for the right-side rail
// ──────────────────────────────────────────────
const STEPS = [
{ id: 'partner', num: '01', title: 'Sign-in screen',
  desc: 'User taps "Continue with Vi" inside the partner app.' },
{ id: 'verifying', num: '02', title: 'Network handshake',
  desc: 'Vi SDK silently verifies the SIM and fetches the MSISDN.' },
{ id: 'consent', num: '03', title: 'Vi consent',
  desc: 'Verified number + per-attribute toggles. User opts in or out of each.' },
{ id: 'dpdp', num: '—', title: 'Notice & rights',
  desc: 'DPDP notice: purpose, withdrawal, grievance officer.' },
{ id: 'done', num: '04', title: 'Signed in',
  desc: 'Sheet dismisses; partner app loads in signed-in state.' },
{ id: 'manage', num: '05', title: 'Manage in Vi app',
  desc: 'Inside the Vi app — review or revoke consent for any app.' }];


const DEMO_PHONE = '+91 98765 43210';
const DEMO_NAME = 'Priya';

// ──────────────────────────────────────────────
// Step rail (right-side annotation)
// ──────────────────────────────────────────────
const StepRail = ({ currentId, onJump, autoplay, onAutoplayChange, onReplay }) => {
  return (
    <div className="rail">
      <div>
        <div style={{
          fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5,
          letterSpacing: 1.4, textTransform: 'uppercase', color: '#8b8e97'
        }}>OTPLESS</div>
        <h2 style={{
          fontFamily: "'DM Sans', system-ui",
          fontSize: 22, fontWeight: 600, letterSpacing: -0.5,
          margin: '6px 0 6px', color: '#0c0d12'
        }}>Login with <span style={{ color: VI.red }}>Vi</span></h2>
        <p style={{ fontSize: 13, color: '#5a5d67', margin: 0, lineHeight: 1.5 }}>Vi SDK verifies the SIM, fetches the number, and collects purpose-bound consent - entirely inside one bottom sheet. DPDP - compliant by design.


        </p>
      </div>

      {/* steps */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {STEPS.filter((s) => s.id !== 'dpdp').map((s, i, arr) => {
          const isCurrent = currentId === s.id || currentId === 'dpdp' && s.id === 'consent';
          const currentIdx = arr.findIndex((x) => x.id === currentId) >= 0 ?
          arr.findIndex((x) => x.id === currentId) :
          arr.findIndex((x) => x.id === 'consent');
          const isPast = i < currentIdx;
          return (
            <button key={s.id} onClick={() => onJump(s.id)} style={{
              display: 'flex', gap: 14, padding: '10px 8px', textAlign: 'left',
              border: 'none', background: isCurrent ? 'rgba(237,28,36,0.06)' : 'transparent',
              borderRadius: 10, cursor: 'pointer', alignItems: 'flex-start',
              transition: 'background .2s ease', fontFamily: 'inherit'
            }}>
              <div style={{
                position: 'relative', display: 'flex', flexDirection: 'column',
                alignItems: 'center', flexShrink: 0, paddingTop: 2
              }}>
                <div style={{
                  width: 20, height: 20, borderRadius: '50%',
                  background: isCurrent || isPast ? VI.red : '#fff',
                  border: `1.5px solid ${isCurrent || isPast ? VI.red : '#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 < arr.length - 1 &&
                <div style={{
                  width: 1.5, flex: 1, minHeight: 22,
                  background: isPast ? VI.red : '#dcd8cf', marginTop: 4
                }} />
                }
              </div>
              <div style={{ flex: 1, paddingBottom: 6 }}>
                <div style={{
                  fontFamily: "'JetBrains Mono', monospace", fontSize: 10,
                  color: '#8b8e97', letterSpacing: 0.5, textTransform: 'uppercase'
                }}>{s.num}</div>
                <div style={{
                  fontFamily: "'DM Sans', system-ui", fontSize: 14,
                  fontWeight: 600, color: '#0c0d12', marginTop: 1
                }}>{s.title}</div>
                <div style={{ fontSize: 11.5, color: '#5a5d67', marginTop: 2, lineHeight: 1.4 }}>
                  {s.desc}
                </div>
              </div>
            </button>);

        })}
      </div>

      {/* controls */}
      <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: 10.5, fontWeight: 500, color: '#8b8e97',
          letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 8
        }}>Playback</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'}
          </button>
        </div>
      </div>

      {/* Pitch chips */}
      <div style={{
        padding: 12, borderRadius: 12,
        background: 'linear-gradient(135deg, rgba(237,28,36,0.06) 0%, rgba(255,210,0,0.08) 100%)',
        border: '1px solid rgba(237,28,36,0.12)'
      }}>
        <div style={{
          fontSize: 10.5, fontWeight: 500, color: '#8b8e97',
          letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 8
        }}>Why this wins</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 7, fontSize: 12, color: '#0c0d12', lineHeight: 1.4 }}>
          {[
          ['2s', 'SNA login · no OTP · no SMS cost'],
          ['DPDP', 'Purpose-bound consent · 1-tap withdraw'],
          ['200M+', 'Vi user base · instant Indian SSO'],
          ['B2B', 'Monetise the Vi identity graph']].
          map(([k, v], i) =>
          <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <div style={{
              minWidth: 38, height: 18,
              background: '#0c0d12', color: '#fff',
              borderRadius: 4, padding: '0 6px',
              fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, fontWeight: 600,
              letterSpacing: 0.4, textTransform: 'uppercase',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
            }}>{k}</div>
              <div>{v}</div>
            </div>
          )}
        </div>
      </div>
    </div>);

};

// ──────────────────────────────────────────────
// Main app
// ──────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "en",
  "showFrame": true,
  "autoplay": false
} /*EDITMODE-END*/;

const App = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [step, setStep] = useState('partner');
  const [autoplay, setAutoplay] = useState(t.autoplay);
  const [connections, setConnections] = useState(DEFAULT_CONNECTIONS);
  const [selectedAppId, setSelectedAppId] = useState(null);

  const [selections, setSelections] = useState(() => {
    const seed = {};
    ATTR_LIST.forEach((a) => {seed[a.id] = a.required || a.defaultOn;});
    return seed;
  });

  const flowRef = useRef(null);
  const lang = t.lang;

  const replay = useCallback(() => {
    clearTimeout(flowRef.current);
    setStep('partner');
    setSelectedAppId(null);
    const seed = {};
    ATTR_LIST.forEach((a) => {seed[a.id] = a.required || a.defaultOn;});
    setSelections(seed);
  }, []);

  // Autoplay timeline
  useEffect(() => {
    if (!autoplay) return;
    const timings = {
      partner: 1400,
      consent: 4500,
      done: 2800,
      manage: 5500
    };
    const next = {
      partner: 'verifying',
      consent: 'done',
      done: 'manage',
      manage: 'partner'
    };
    if (step === 'verifying' || step === 'dpdp') return; // verifying owns its timer; dpdp pauses autoplay
    flowRef.current = setTimeout(() => {
      if (step === 'manage' && selectedAppId === null) {
        setSelectedAppId('bazaar');
        flowRef.current = setTimeout(() => setStep(next[step]), 2400);
      } else {
        if (step === 'manage') setSelectedAppId(null);
        setStep(next[step]);
      }
    }, timings[step]);
    return () => clearTimeout(flowRef.current);
  }, [step, autoplay, selectedAppId]);

  useEffect(() => {setTweak('autoplay', autoplay);}, [autoplay]);

  // Handlers
  const handleJump = (s) => {
    setAutoplay(false);
    if (s === 'manage') setSelectedAppId(null);
    setStep(s);
  };

  const handleToggle = (id, v) => setSelections((prev) => ({ ...prev, [id]: v }));

  const handleRevoke = (id) => {
    setConnections((prev) => prev.map((c) =>
    c.id === id ? { ...c, revoked: true, lastSeen: 'Revoked just now', shares: [c.shares[0]] } : c
    ));
  };

  // Map outer step → sheet-step (only meaningful when sheet is open)
  const SHEET_STEPS = ['verifying', 'consent', 'dpdp', 'done'];
  const isSheetOpen = SHEET_STEPS.includes(step);

  // ──────────────────────────────────────────────
  // Render
  // ──────────────────────────────────────────────
  const renderSurface = () => {
    // The "Manage in Vi app" step lives in the Vi app context (not partner-overlay)
    if (step === 'manage') {
      return (
        <ViManageConsent
          phone={DEMO_PHONE} connections={connections}
          onRevoke={handleRevoke}
          onSelect={(id) => setSelectedAppId(id)}
          selectedAppId={selectedAppId} lang={lang} />);


    }

    // Everything else renders the partner app as the base layer.
    // For 'done' (signed in) the home variant is shown.
    const partner = step === 'done' ?
    <BazaarHome phone={DEMO_PHONE} name={DEMO_NAME} lang={lang} /> :
    <BazaarSignIn onLoginWithVi={() => {setAutoplay(false);setStep('verifying');}} lang={lang} />;

    if (!isSheetOpen || step === 'done') {
      // 'done' shows the BazaarHome without a sheet (sheet has already dismissed)
      return <div style={{ position: 'relative', height: '100%' }}>{partner}</div>;
    }

    // Sheet open over partner app
    return (
      <div style={{ position: 'relative', height: '100%' }}>
        {partner}
        <ViSdkSheet
          phone={DEMO_PHONE} partnerName="Bazaar"
          sheetStep={step}
          selections={selections} onToggle={handleToggle}
          onVerified={() => {setStep('consent');}}
          onContinueFromConsent={() => {setStep('done');}}
          onShareOnlyRequired={() => {
            ATTR_LIST.forEach((a) => {if (!a.required) handleToggle(a.id, false);});
            setStep('done');
          }}
          onSeeDpdp={() => {setAutoplay(false);setStep('dpdp');}}
          onBackFromDpdp={() => {setStep('consent');}}
          onCancel={() => {setAutoplay(false);setStep('partner');}}
          lang={lang} />
        
      </div>);

  };

  return (
    <div className="stage" data-screen-label={`Login with Vi · ${step}`}>
      <div className="phone-col">
        {t.showFrame ?
        <PhoneFrame dark={false} width={372} height={760}>
              <div key={step === 'partner' || step === 'done' || step === 'manage' ? step : 'sheet-open'}
          className="screen-enter screen-enter-active" style={{ height: '100%' }}>
                {renderSurface()}
              </div>
            </PhoneFrame> :
        <div style={{
          width: 372, height: 720, borderRadius: 28, overflow: 'hidden',
          boxShadow: '0 30px 80px -20px rgba(20,22,30,0.25)',
          background: '#fff'
        }}>
              <div key={step === 'partner' || step === 'done' || step === 'manage' ? step : 'sheet-open'}
          className="screen-enter screen-enter-active" style={{ height: '100%' }}>
                {renderSurface()}
              </div>
            </div>
        }
      </div>
      <StepRail
        currentId={step}
        onJump={handleJump}
        autoplay={autoplay}
        onAutoplayChange={setAutoplay}
        onReplay={() => {setAutoplay(true);replay();}} />
      

      <TweaksPanel title="Tweaks">
        <TweakSection label="Language" />
        <TweakRadio
          label="Locale"
          value={t.lang}
          options={[{ value: 'en', label: 'English' }, { value: 'hi', label: 'हिन्दी' }]}
          onChange={(v) => setTweak('lang', v)} />
        
        <TweakSection label="Stage" />
        <TweakToggle label="Device frame" value={t.showFrame} onChange={(v) => setTweak('showFrame', v)} />
        <TweakToggle label="Autoplay" value={autoplay} onChange={setAutoplay} />
        <TweakSection label="Jump to step" />
        <TweakSelect
          label="Step"
          value={step}
          options={STEPS.map((s) => ({ value: s.id, label: `${s.num} · ${s.title}` }))}
          onChange={(v) => handleJump(v)} />
        
      </TweaksPanel>
    </div>);

};

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