// flow-guided.jsx — Direction A: Field Kit (light guided wizard)
// Exports window.FlowGuided

function FlowGuided() {
  const [screen, setScreen] = React.useState(0); // 0=welcome 1-5=steps 6=success
  const [dir, setDir] = React.useState(1);
  const [wifiSub, setWifiSub] = React.useState('detect'); // detect|found|typing|connecting|done
  const [tileSub, setTileSub] = React.useState('idle'); // idle|connecting|done
  const [testSub, setTestSub] = React.useState('idle'); // idle|printing|receipt|tapping|done
  const [storeName, setStoreName] = React.useState('');
  const [address, setAddress] = React.useState('');
  const [sector, setSector] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [pwTyping, setPwTyping] = React.useState(false);

  const animKey = React.useRef(0);

  React.useEffect(() => {
    if (screen === 2) {
      setWifiSub('detect');
      const t = setTimeout(() => setWifiSub('found'), 1400);
      return () => clearTimeout(t);
    }
    if (screen === 4) { setTileSub('idle'); }
    if (screen === 5) { setTestSub('idle'); }
  }, [screen]);

  const go = (n) => { setDir(n > screen ? 1 : -1); animKey.current++; setScreen(n); };
  const next = () => go(screen + 1);
  const back = () => go(screen - 1);

  const typeIn = (setter, val, delay = 35) => {
    let i = 0;
    const t = setInterval(() => {
      i++;
      setter(val.slice(0, i));
      if (i >= val.length) clearInterval(t);
    }, delay);
  };

  const handlePwTap = () => {
    if (pwTyping || password.length > 0) return;
    setPwTyping(true);
    typeIn(setPassword, 'mystore123', 55);
    setTimeout(() => setPwTyping(false), 700);
  };

  const handleConnect = () => {
    setWifiSub('connecting');
    setTimeout(() => { setWifiSub('done'); }, 1500);
  };

  const handleTilePower = () => {
    setTileSub('connecting');
    setTimeout(() => setTileSub('done'), 1600);
  };

  const handleSimPrint = () => {
    setTestSub('printing');
    setTimeout(() => setTestSub('receipt'), 1600);
  };
  const handleTapTile = () => {
    setTestSub('tapping');
    setTimeout(() => setTestSub('done'), 1400);
  };

  const detailsDone = storeName.length > 0 && address.length > 0 && sector.length > 0;

  const GREEN = '#15803d', G50 = '#f0fdf4', G100 = '#dcfce7', G700 = GREEN;
  const N50 = '#fafaf7', N100 = '#f4f4ef', N200 = '#e8e8e1', N500 = '#72726a', N700 = '#3d3d38', N950 = '#0f0f0b';
  const fd = window.fontDisplay, fb = window.fontBody;

  // Header used in steps 1-5
  const StepHeader = ({ step }) => (
    <div style={{ padding: '54px 20px 0' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <button onClick={back} style={{ width: 36, height: 36, border: 'none', background: N100, borderRadius: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="arrowLeft" size={18} color={N700} stroke={2} />
        </button>
        <span style={{ fontFamily: fb, fontSize: 12, fontWeight: 600, color: N500, letterSpacing: '0.04em' }}>STEP {step} OF 5</span>
        <div style={{ width: 36 }} />
      </div>
      <ProgressBar step={step} total={5} accent={GREEN} track={N200} />
    </div>
  );

  // Illustration band
  const IlloBand = ({ children, bg = G50, h = 190 }) => (
    <div style={{ background: bg, margin: '18px 20px 0', borderRadius: 20, height: h, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', border: `1px solid ${N200}` }}>
      {children}
    </div>
  );

  // Section heading
  const Heading = ({ title, sub }) => (
    <div style={{ padding: '18px 20px 0' }}>
      <div style={{ fontFamily: fd, fontWeight: 800, fontSize: 24, color: N950, letterSpacing: '-0.02em', lineHeight: 1.15, marginBottom: 7, textWrap: 'pretty' }}>{title}</div>
      {sub && <div style={{ fontFamily: fb, fontSize: 14, color: N500, lineHeight: 1.6 }}>{sub}</div>}
    </div>
  );

  // Footer CTA area
  const Footer = ({ children }) => (
    <div style={{ padding: '16px 20px 32px', marginTop: 'auto' }}>{children}</div>
  );

  // ── Screens ──────────────────────────────────────────────
  const screens = {
    // WELCOME
    0: (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: N50, paddingTop: 56 }}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20, padding: '0 28px' }}>
          <div style={{ width: 90, height: 90, borderRadius: 26, background: GREEN, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 12px 36px rgba(21,128,61,0.22)' }}>
            <RaseedMark size={46} color="#fff" faded={false} />
          </div>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontFamily: fd, fontWeight: 900, fontSize: 32, color: N950, letterSpacing: '-0.03em', lineHeight: 1.1 }}>Set up Raseed</div>
            <div style={{ fontFamily: fb, fontSize: 15, color: N500, marginTop: 10, lineHeight: 1.6 }}>Under 10 minutes from unboxing to your first digital receipt.</div>
          </div>
          <div style={{ width: '100%', background: '#fff', borderRadius: 16, padding: '14px 18px', border: `1px solid ${N200}` }}>
            <div style={{ fontFamily: fb, fontSize: 11, fontWeight: 700, color: GREEN, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>What's in the box</div>
            {[['box','Print Bridge', 'The USB interceptor'], ['receipt','Raseed Tile', 'The NFC customer pad']].map(([icon, name, desc]) => (
              <div key={name} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
                <div style={{ width: 34, height: 34, borderRadius: 10, background: G50, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name={icon} size={18} color={GREEN} stroke={1.75} />
                </div>
                <div>
                  <div style={{ fontFamily: fb, fontSize: 14, fontWeight: 600, color: N950 }}>{name}</div>
                  <div style={{ fontFamily: fb, fontSize: 12, color: N500 }}>{desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <Footer>
          <PrimaryButton onClick={next} accent="#15803d" accentHover="#166534" icon="arrowRight">Start setup</PrimaryButton>
          <div style={{ textAlign: 'center', marginTop: 12 }}>
            <span style={{ fontFamily: fb, fontSize: 13, color: N500, cursor: 'pointer' }}>I already have an account — sign in</span>
          </div>
        </Footer>
      </div>
    ),

    // STEP 1 — PRINT BRIDGE
    1: (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <StepHeader step={1} />
        <IlloBand h={170}><BridgeDiagram dark={false} /></IlloBand>
        <Heading title="Plug in the Print Bridge" sub="Sit it between your POS and printer. The cashier sees no change." />
        <div style={{ padding: '16px 20px 0' }}>
          {['Unplug the USB cable from POS to printer', 'Plug the Bridge into the POS USB port', 'Plug the printer cable into the Bridge'].map((t, i) => (
            <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 13 }}>
              <div style={{ width: 24, height: 24, borderRadius: 999, background: G100, border: `1.5px solid #86efac`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                <span style={{ fontFamily: fd, fontWeight: 800, fontSize: 12, color: GREEN }}>{i + 1}</span>
              </div>
              <span style={{ fontFamily: fb, fontSize: 14, color: N700, lineHeight: 1.55 }}>{t}</span>
            </div>
          ))}
        </div>
        <Footer>
          <PrimaryButton onClick={next} icon="checkCircle">Bridge is plugged in</PrimaryButton>
        </Footer>
      </div>
    ),

    // STEP 2 — WIFI
    2: (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <StepHeader step={2} />
        <div style={{ padding: '20px 20px 0' }}>
          <div style={{ fontFamily: fd, fontWeight: 800, fontSize: 24, color: N950, letterSpacing: '-0.02em', lineHeight: 1.15, marginBottom: 7 }}>Connect to store WiFi</div>
        </div>

        {(wifiSub === 'detect') && (
          <div style={{ margin: '14px 20px', background: G50, borderRadius: 16, padding: '18px', border: `1px solid ${G100}`, display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 38, height: 38, borderRadius: 12, background: G100, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="#15803d" strokeWidth="2">
                <circle cx="11" cy="11" r="4"><animate attributeName="r" values="4;6;4" dur="1.2s" repeatCount="indefinite"/></circle>
                <circle cx="11" cy="11" r="9" opacity="0.4"><animate attributeName="r" values="9;11;9" dur="1.2s" repeatCount="indefinite"/></circle>
              </svg>
            </div>
            <div>
              <div style={{ fontFamily: fb, fontWeight: 600, fontSize: 14, color: GREEN }}>Scanning for Print Bridge…</div>
              <div style={{ fontFamily: fb, fontSize: 12, color: N500, marginTop: 3 }}>Make sure it has power</div>
            </div>
          </div>
        )}
        {(wifiSub === 'found' || wifiSub === 'typing' || wifiSub === 'connecting' || wifiSub === 'done') && (
          <div style={{ margin: '14px 20px 0', background: G50, borderRadius: 16, padding: '14px 16px', border: `1px solid #86efac`, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: GREEN, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="wifi" size={18} color="#fff" stroke={2} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: fb, fontWeight: 700, fontSize: 14, color: N950 }}>Bridge-7A2 found</div>
              <div style={{ fontFamily: fb, fontSize: 12, color: N500 }}>Ready to connect</div>
            </div>
            <Icon name="checkCircle" size={20} color="#22c55e" stroke={2} />
          </div>
        )}

        {(wifiSub === 'found' || wifiSub === 'typing' || wifiSub === 'connecting' || wifiSub === 'done') && (
          <div style={{ padding: '16px 20px 0' }}>
            <div style={{ fontFamily: fb, fontSize: 12, fontWeight: 600, color: N500, marginBottom: 6, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Store WiFi password</div>
            <div onClick={handlePwTap} style={{ display: 'flex', alignItems: 'center', gap: 12, background: '#fff', border: `1.5px solid ${password ? GREEN : N200}`, borderRadius: 13, padding: '13px 15px', cursor: 'text', transition: 'border-color 200ms' }}>
              <Icon name="lock" size={18} color={password ? GREEN : N500} stroke={1.75} />
              <span style={{ fontFamily: fb, fontSize: 15, color: password ? N950 : N500, letterSpacing: password ? '0.15em' : 0 }}>
                {password ? '•'.repeat(password.length) : 'Tap to enter password'}
              </span>
            </div>
          </div>
        )}

        {wifiSub === 'connecting' && (
          <div style={{ margin: '14px 20px 0', background: '#fffbeb', border: '1px solid #fef3c7', borderRadius: 14, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="#d97706" strokeWidth="2"><circle cx="9" cy="9" r="7.5"/><line x1="9" y1="5" x2="9" y2="9.5"><animate attributeName="y2" values="5;12;5" dur="1s" repeatCount="indefinite"/></line></svg>
            <span style={{ fontFamily: fb, fontSize: 14, fontWeight: 500, color: '#b45309' }}>Connecting to WiFi…</span>
          </div>
        )}
        {wifiSub === 'done' && (
          <div style={{ margin: '14px 20px 0', background: G50, border: '1px solid #86efac', borderRadius: 14, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name="checkCircle" size={18} color="#22c55e" stroke={2} />
            <span style={{ fontFamily: fb, fontSize: 14, fontWeight: 600, color: GREEN }}>Bridge connected to WiFi!</span>
          </div>
        )}

        <Footer>
          {wifiSub === 'found' && <PrimaryButton onClick={handleConnect} disabled={!password} icon="arrowRight">Connect Bridge</PrimaryButton>}
          {wifiSub === 'connecting' && <PrimaryButton disabled icon={null}><span style={{ opacity: 0.7 }}>Connecting…</span></PrimaryButton>}
          {wifiSub === 'done' && <PrimaryButton onClick={next} icon="arrowRight">Continue</PrimaryButton>}
          {wifiSub === 'detect' && <PrimaryButton disabled icon={null}><span style={{ opacity: 0.7 }}>Scanning…</span></PrimaryButton>}
          {wifiSub === 'typing' && <PrimaryButton disabled={!password} onClick={handleConnect} icon="arrowRight">Connect Bridge</PrimaryButton>}
        </Footer>
      </div>
    ),

    // STEP 3 — MERCHANT DETAILS
    3: (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <StepHeader step={3} />
        <Heading title="Merchant details" sub="30 seconds. We only need the essentials." />
        <div style={{ padding: '18px 20px 0', display: 'flex', flexDirection: 'column', gap: 13 }}>
          {[['Store name', 'storeName', 'Imtiaz Super Market', setStoreName, storeName],
            ['Address', 'address', 'Clifton Block 5, Karachi', setAddress, address]].map(([label, key, sample, setter, val]) => (
            <div key={key}>
              <div style={{ fontFamily: fb, fontSize: 12, fontWeight: 600, color: N500, marginBottom: 5, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</div>
              <div onClick={() => { if (!val) typeIn(setter, sample, 38); }}
                style={{ background: '#fff', border: `1.5px solid ${val ? GREEN : N200}`, borderRadius: 13, padding: '13px 15px', cursor: val ? 'default' : 'text', transition: 'border-color 200ms', display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontFamily: fb, fontSize: 15, color: val ? N950 : N500, flex: 1 }}>{val || `Tap to enter ${label.toLowerCase()}`}</span>
                {val && <Icon name="check" size={16} color="#22c55e" stroke={2.5} />}
              </div>
            </div>
          ))}
          <div>
            <div style={{ fontFamily: fb, fontSize: 12, fontWeight: 600, color: N500, marginBottom: 8, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Sector</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {['Retail', 'F&B', 'Pharmacy', 'Services', 'Other'].map(s => (
                <button key={s} onClick={() => setSector(s)} style={{
                  padding: '9px 16px', borderRadius: 999, border: `1.5px solid ${sector === s ? GREEN : N200}`,
                  background: sector === s ? G50 : '#fff', color: sector === s ? GREEN : N700,
                  fontFamily: fb, fontWeight: sector === s ? 700 : 500, fontSize: 14, cursor: 'pointer', transition: 'all 180ms',
                }}>{s}</button>
              ))}
            </div>
          </div>
        </div>
        <Footer>
          <PrimaryButton onClick={next} disabled={!detailsDone} icon="arrowRight">Save and continue</PrimaryButton>
        </Footer>
      </div>
    ),

    // STEP 4 — TILE
    4: (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <StepHeader step={4} />
        <IlloBand h={195}><TileDiagram dark={false} ripple={tileSub === 'done'} /></IlloBand>
        <Heading title="Place the Raseed Tile" sub={tileSub === 'done' ? 'The Tile is online and ready.' : 'Put it on the counter next to the payment terminal, then plug in USB power.'} />
        {tileSub === 'connecting' && (
          <div style={{ margin: '12px 20px 0', background: G50, border: `1px solid ${G100}`, borderRadius: 14, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
            <svg width="16" height="16" fill="none" stroke={GREEN} strokeWidth="2"><circle cx="8" cy="8" r="6"><animate attributeName="r" values="6;8;6" dur="1.2s" repeatCount="indefinite" /></circle></svg>
            <span style={{ fontFamily: fb, fontSize: 14, fontWeight: 500, color: GREEN }}>Connecting to WiFi…</span>
          </div>
        )}
        {tileSub === 'done' && (
          <div style={{ margin: '12px 20px 0', background: G50, border: '1px solid #86efac', borderRadius: 14, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name="checkCircle" size={18} color="#22c55e" stroke={2} />
            <span style={{ fontFamily: fb, fontSize: 14, fontWeight: 600, color: GREEN }}>Tile online — auto-connected!</span>
          </div>
        )}
        <Footer>
          {tileSub === 'idle' && <PrimaryButton onClick={handleTilePower} icon="bolt">Tile is powered on</PrimaryButton>}
          {tileSub === 'connecting' && <PrimaryButton disabled icon={null}><span style={{ opacity: 0.7 }}>Connecting…</span></PrimaryButton>}
          {tileSub === 'done' && <PrimaryButton onClick={next} icon="arrowRight">Continue</PrimaryButton>}
        </Footer>
      </div>
    ),

    // STEP 5 — TEST TRANSACTION
    5: (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <StepHeader step={5} />
        <div style={{ margin: '18px 20px 0', background: testSub === 'receipt' || testSub === 'tapping' || testSub === 'done' ? G50 : N100, borderRadius: 20, height: 185, display: 'flex', alignItems: 'center', justifyContent: 'center', border: `1px solid ${testSub === 'receipt' || testSub === 'done' ? '#86efac' : N200}`, overflow: 'hidden', transition: 'all 400ms' }}>
          {(testSub === 'idle' || testSub === 'printing') && <PrinterDevice w={110} dark={false} />}
          {testSub === 'receipt' && (
            <div style={{ textAlign: 'center' }}>
              <div style={{ width: 56, height: 56, borderRadius: 20, background: GREEN, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 8px' }}><RaseedMark size={28} color="#fff" faded={false} /></div>
              <div style={{ fontFamily: fb, fontSize: 13, fontWeight: 700, color: GREEN }}>Receipt received!</div>
              <div style={{ fontFamily: fb, fontSize: 12, color: N500, marginTop: 3 }}>tryraseed.com/t?id=IMZ07</div>
            </div>
          )}
          {(testSub === 'tapping' || testSub === 'done') && <PhoneTap dark={false} />}
        </div>
        <Heading
          title={testSub === 'idle' ? 'Run a test transaction' : testSub === 'printing' ? 'Printing…' : testSub === 'receipt' ? 'Receipt captured!' : testSub === 'tapping' ? 'Tap the Tile…' : 'It works!'}
          sub={testSub === 'idle' ? 'Ask the cashier to ring up one item and hit print.' : testSub === 'receipt' ? 'Now show the customer tap experience.' : testSub === 'done' ? "The receipt opened instantly. That's the whole experience." : undefined}
        />
        <Footer>
          {testSub === 'idle' && <PrimaryButton onClick={handleSimPrint} icon="printer">Simulate print job</PrimaryButton>}
          {testSub === 'printing' && <PrimaryButton disabled icon={null}><span style={{ opacity: 0.7 }}>Waiting for print…</span></PrimaryButton>}
          {testSub === 'receipt' && <PrimaryButton onClick={handleTapTile} icon="device">Tap the Tile with phone</PrimaryButton>}
          {testSub === 'tapping' && <PrimaryButton disabled icon={null}><span style={{ opacity: 0.7 }}>Opening receipt…</span></PrimaryButton>}
          {testSub === 'done' && <PrimaryButton onClick={next} icon="sparkles" accent="#16a34a">You're live — go to dashboard</PrimaryButton>}
        </Footer>
      </div>
    ),

    // SUCCESS / DASHBOARD — light theme
    6: (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', position: 'relative', paddingTop: 56, background: N50 }}>
        <Confetti count={30} />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '20px 24px 0', zIndex: 10, position: 'relative' }}>
          <div style={{ fontFamily: fd, fontWeight: 900, fontSize: 52, color: GREEN, letterSpacing: '-0.04em', lineHeight: 1, marginBottom: 6 }}>Done.</div>
          <div style={{ fontFamily: fd, fontWeight: 700, fontSize: 22, color: N950, letterSpacing: '-0.02em', marginBottom: 16 }}>Store is live.</div>
          <div style={{ fontFamily: fb, fontSize: 14, color: N500, lineHeight: 1.65, marginBottom: 28 }}>Every print job now delivers a digital receipt to the customer's phone in under a second.</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[['Bridge', 'Intercepting', GREEN], ['Tile', 'Online', GREEN], ['WiFi', 'Connected', GREEN], ['FBR', 'Compliant', '#2563eb']].map(([l, s, c]) => (
              <div key={l} style={{ background: '#fff', borderRadius: 14, padding: '14px 16px', border: `1px solid ${N200}` }}>
                <div style={{ fontFamily: fb, fontSize: 12, color: N500, marginBottom: 4 }}>{l}</div>
                <div style={{ fontFamily: fb, fontSize: 14, fontWeight: 700, color: c }}>{s}</div>
              </div>
            ))}
          </div>
        </div>
        <Footer>
          <PrimaryButton onClick={() => setScreen(0)} icon="arrowRight">Open dashboard</PrimaryButton>
        </Footer>
      </div>
    ),
  };

  const screenBg = N50;
  const isLight = true;

  return (
    <PhoneShell statusDark={false} screenBg={screenBg} barTint="rgba(250,250,247,0.85)">
      <div key={`s${screen}-${animKey.current}`} style={{ flex: 1, display: 'flex', flexDirection: 'column', animation: dir > 0 ? 'screenSlideIn 280ms cubic-bezier(0.4,0,0.2,1) both' : 'screenSlideBack 280ms cubic-bezier(0.4,0,0.2,1) both' }}>
        {screens[screen]}
      </div>
    </PhoneShell>
  );
}

Object.assign(window, { FlowGuided });
