// Active Job — the centerpiece. OTP gate + live billing + state machine.

const STATES = [
  { id: 'enroute',    label: 'En route',          sub: 'Heading to customer',     icon: '🛵' },
  { id: 'arrived',    label: 'Arrived',           sub: 'OTP to begin inspection', icon: '📍' },
  { id: 'inspecting', label: 'Inspecting',        sub: 'Diagnosing the issue',    icon: '🔍' },
  { id: 'estimate',   label: 'Estimate sent',     sub: 'Awaiting customer cap',   icon: '📋' },
  { id: 'working',    label: 'Live work',         sub: 'Server timer running',    icon: '⚡' },
  { id: 'complete',   label: 'Completion OTP',    sub: 'Customer confirms done',  icon: '✓'  },
  { id: 'paid',       label: 'Paid',              sub: 'Released to wallet',      icon: '💰' },
];

// ── Live timer hook ───────────────────────────────────────────
const useTicker = (active, startSec = 0) => {
  const [s, setS] = React.useState(startSec);
  React.useEffect(() => {
    if (!active) return;
    const id = setInterval(() => setS(v => v + 1), 1000);
    return () => clearInterval(id);
  }, [active]);
  return s;
};
const fmtTime = (s) => `${String(Math.floor(s/60)).padStart(2,'0')}:${String(s%60).padStart(2,'0')}`;

// ── OTP Pad modal ─────────────────────────────────────────────
const OTPModal = ({ open, title, sub, expected = '4729', onClose, onSuccess }) => {
  const [code, setCode] = React.useState('');
  const [err, setErr] = React.useState(false);
  const [success, setSuccess] = React.useState(false);

  React.useEffect(() => { if (open) { setCode(''); setErr(false); setSuccess(false); } }, [open]);

  const press = (d) => {
    if (success || code.length >= 4) return;
    const n = code + d;
    setCode(n);
    if (n.length === 4) {
      setTimeout(() => {
        if (n === expected) {
          setSuccess(true);
          setTimeout(() => onSuccess(), 900);
        } else {
          setErr(true);
          setTimeout(() => { setCode(''); setErr(false); }, 600);
        }
      }, 200);
    }
  };
  const back = () => setCode(c => c.slice(0, -1));

  if (!open) return null;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100, display: 'flex', flexDirection: 'column',
      background: 'rgba(10,1,24,0.92)', backdropFilter: 'blur(20px)',
      animation: 'fadeIn .25s',
    }}>
      <div style={{ flex: 1, padding: 24, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div onClick={onClose} style={{
          position: 'absolute', top: 56, right: 18, width: 36, height: 36, borderRadius: '50%',
          background: 'rgba(255,255,255,0.06)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', color: Z.text2, border: `0.5px solid ${Z.border}`,
        }}><I.x size={18}/></div>

        {/* Lock icon */}
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{
            width: 72, height: 72, borderRadius: 22, margin: '0 auto 18px',
            background: success ? 'rgba(16,185,129,0.18)' : 'rgba(124,58,237,0.18)',
            border: `1px solid ${success ? 'rgba(16,185,129,0.5)' : Z.borderStrong}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: success ? Z.success : Z.brandLite,
            boxShadow: success ? `0 0 40px rgba(16,185,129,0.4)` : `0 0 40px ${Z.brand}55`,
            transition: 'all .3s',
          }}>
            {success ? <I.check size={36} stroke={2.5}/> : <I.lock size={32}/>}
          </div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 2, color: Z.brandLite, textTransform: 'uppercase', marginBottom: 8 }}>
            Trust gate
          </div>
          <div style={{ fontSize: 22, fontWeight: 700, color: Z.text, letterSpacing: -0.5, marginBottom: 8 }}>{title}</div>
          <div style={{ fontSize: 13, color: Z.text3, lineHeight: 1.5, maxWidth: 280, margin: '0 auto' }}>{sub}</div>
        </div>

        {/* digits */}
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginBottom: 32, animation: err ? 'shake .4s' : 'none' }}>
          {[0,1,2,3].map(i => {
            const filled = i < code.length;
            return (
              <div key={i} style={{
                width: 58, height: 68, borderRadius: 14,
                background: filled ? 'rgba(124,58,237,0.18)' : 'rgba(20,8,40,0.6)',
                border: `1.5px solid ${err ? Z.danger : filled ? Z.brand : Z.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                ...mono, fontSize: 26, fontWeight: 600, color: Z.text,
                boxShadow: filled ? `0 0 20px ${Z.brand}44, inset 0 0 12px ${Z.brand}22` : 'none',
                transition: 'all .15s',
              }}>{success ? '✓' : filled ? '•' : ''}</div>
            );
          })}
        </div>

        {/* hint */}
        <div style={{ textAlign: 'center', fontSize: 11, color: Z.text4, marginBottom: 20 }}>
          OTP shared with customer · expires in 2:00
        </div>

        {/* keypad */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, maxWidth: 280, margin: '0 auto', width: '100%' }}>
          {['1','2','3','4','5','6','7','8','9'].map(d => (
            <div key={d} onClick={() => press(d)} style={{
              padding: '16px 0', textAlign: 'center', borderRadius: 14,
              background: 'rgba(26,11,59,0.55)', border: `0.5px solid ${Z.border}`,
              fontSize: 22, fontWeight: 600, color: Z.text, cursor: 'pointer',
              fontFamily: Z.mono,
            }}>{d}</div>
          ))}
          <div />
          <div onClick={() => press('0')} style={{
            padding: '16px 0', textAlign: 'center', borderRadius: 14,
            background: 'rgba(26,11,59,0.55)', border: `0.5px solid ${Z.border}`,
            fontSize: 22, fontWeight: 600, color: Z.text, cursor: 'pointer', fontFamily: Z.mono,
          }}>0</div>
          <div onClick={back} style={{
            padding: '16px 0', textAlign: 'center', borderRadius: 14,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: Z.text3, cursor: 'pointer',
          }}>⌫</div>
        </div>

        <div style={{ textAlign: 'center', marginTop: 24, fontSize: 11, color: Z.text4 }}>
          Hint for demo: <span style={{ ...mono, color: Z.brandLite }}>4729</span>
        </div>
      </div>
    </div>
  );
};

// ── State timeline ────────────────────────────────────────────
const StateTimeline = ({ current }) => {
  const curIdx = STATES.findIndex(s => s.id === current);
  return (
    <div style={{ display: 'flex', gap: 0, padding: '4px 0' }}>
      {STATES.map((s, i) => {
        const done = i < curIdx;
        const active = i === curIdx;
        const lock = !done && !active;
        return (
          <div key={s.id} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative' }}>
            {/* connector */}
            {i > 0 && (
              <div style={{
                position: 'absolute', left: '-50%', right: '50%', top: 9, height: 2,
                background: done || active ? Z.gradient : Z.border,
              }} />
            )}
            {/* node */}
            <div style={{
              width: active ? 20 : 14, height: active ? 20 : 14, borderRadius: '50%',
              background: done ? Z.gradient : active ? Z.gradient : 'rgba(20,8,40,0.6)',
              border: `1.5px solid ${active ? '#fff' : done ? 'transparent' : Z.border}`,
              boxShadow: active ? `0 0 14px ${Z.brand}, 0 0 0 4px rgba(124,58,237,0.25)` : 'none',
              transition: 'all .3s', zIndex: 2,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {done && <div style={{ width: 5, height: 5, borderRadius: '50%', background: '#fff' }} />}
              {lock && <div style={{ width: 4, height: 4, borderRadius: '50%', background: Z.text4 }}/>}
            </div>
            {active && (
              <div style={{
                fontSize: 8.5, fontWeight: 700, color: Z.brandLite, marginTop: 6,
                letterSpacing: 0.6, textTransform: 'uppercase',
              }}>Now</div>
            )}
          </div>
        );
      })}
    </div>
  );
};

// ── Main Active Job screen ────────────────────────────────────
const ActiveJob = ({ nav, job, initialStage = 'enroute', reimagined }) => {
  const j = job || JOB_FEED[0];
  const [stage, setStage] = React.useState(initialStage);
  const [otpModal, setOtpModal] = React.useState(null);
  const stageInfo = STATES.find(s => s.id === stage) || STATES[0];
  const stageIdx = STATES.findIndex(s => s.id === stage);

  // Live billing only while 'working'
  const working = stage === 'working';
  const secs = useTicker(working);
  const estimate = 980;
  const rate = 12; // ₹/min
  const live = Math.min(rate * (secs / 60), estimate);
  const pct = (live / estimate) * 100;

  const advance = () => {
    const next = STATES[stageIdx + 1];
    if (next) setStage(next.id);
  };

  return (
    <div style={{ padding: '0 0 110px', position: 'relative' }}>
      {/* Header */}
      <div style={{ padding: '8px 16px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div onClick={() => nav.back()} style={{
          width: 38, height: 38, borderRadius: '50%', background: 'rgba(20,8,40,0.7)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: Z.text, cursor: 'pointer', border: `0.5px solid ${Z.border}`,
        }}><I.chevL size={20}/></div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: Z.text3 }}>Active job</div>
          <div style={{ ...mono, fontSize: 13, fontWeight: 600, color: Z.text }}>#J-{j.id} · {j.cat}</div>
        </div>
        <Pill tone="brand">{stageInfo.icon} {stageInfo.label}</Pill>
      </div>

      {/* Timeline */}
      <div style={{ padding: '0 18px 18px' }}>
        <StateTimeline current={stage} />
      </div>

      {/* Status hero card */}
      <div style={{ padding: '0 18px' }}>
        <div style={{
          padding: 18, borderRadius: 20, position: 'relative', overflow: 'hidden',
          background: 'linear-gradient(160deg, rgba(124,58,237,0.18), rgba(236,72,153,0.06))',
          border: `1px solid ${Z.brand}`,
          marginBottom: 14,
        }}>
          {reimagined && (
            <div style={{
              position: 'absolute', inset: 0, opacity: 0.2,
              backgroundImage: `linear-gradient(${Z.brandLite} 1px, transparent 1px), linear-gradient(90deg, ${Z.brandLite} 1px, transparent 1px)`,
              backgroundSize: '20px 20px',
              maskImage: 'radial-gradient(ellipse at 100% 0%, black, transparent 70%)',
              WebkitMaskImage: 'radial-gradient(ellipse at 100% 0%, black, transparent 70%)',
            }} />
          )}
          <div style={{ position: 'relative' }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.8, color: Z.brandLite, textTransform: 'uppercase', marginBottom: 6 }}>{stageInfo.sub}</div>
            <div style={{ fontSize: 24, fontWeight: 700, color: Z.text, letterSpacing: -0.5, marginBottom: 16 }}>{stageInfo.label}</div>

            {/* per-stage content */}
            {stage === 'enroute' && (
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14, fontSize: 12, color: Z.text2 }}>
                  <span>📍 1.8 km · ~7 min</span>
                  <span style={mono}>ETA 7:23 PM</span>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button style={{ ...btnGhostStyle, flex: 1 }}><I.phone size={14} style={{verticalAlign:'-3px'}}/> Call</button>
                  <button style={{ ...btnGhostStyle, flex: 1 }}><I.nav size={14} style={{verticalAlign:'-3px'}}/> Navigate</button>
                  <button onClick={() => setStage('arrived')} style={{ ...btnPrimaryStyle, flex: 1.4 }}>I've arrived</button>
                </div>
              </div>
            )}

            {stage === 'arrived' && (
              <div>
                <div style={{ fontSize: 12, color: Z.text2, lineHeight: 1.5, marginBottom: 14 }}>
                  Ask the customer for their <strong style={{ color: Z.text }}>4-digit start OTP</strong> to begin inspection.
                </div>
                <button onClick={() => setOtpModal({ kind: 'start' })} style={{ ...btnPrimaryStyle, width: '100%' }}>
                  <I.lock size={14} style={{verticalAlign:'-3px', marginRight: 6}}/> Enter start OTP
                </button>
              </div>
            )}

            {stage === 'inspecting' && (
              <div>
                <div style={{ fontSize: 12, color: Z.text2, lineHeight: 1.5, marginBottom: 14 }}>
                  Diagnose the issue and prepare a transparent estimate for the customer.
                </div>
                <button onClick={() => setStage('estimate')} style={{ ...btnPrimaryStyle, width: '100%' }}>
                  Submit estimate →
                </button>
              </div>
            )}

            {stage === 'estimate' && (
              <div>
                <div style={{ padding: 12, borderRadius: 12, background: 'rgba(0,0,0,0.25)', marginBottom: 12 }}>
                  {[['Labour (≈75 min)', '₹720'],['Materials (washer, joint)', '₹180'],['Service fee', '₹80']].map(([l,v]) => (
                    <div key={l} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontSize: 12, color: Z.text2 }}>
                      <span>{l}</span><span style={mono}>{v}</span>
                    </div>
                  ))}
                  <div style={{ height: 1, background: Z.border, margin: '8px 0' }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, fontWeight: 700, color: Z.text }}>
                    <span>Cap (max)</span><span style={mono}>₹980</span>
                  </div>
                </div>
                <div style={{ fontSize: 11, color: Z.text3, marginBottom: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
                  <I.clock size={12} color={Z.text3}/> Waiting for customer approval…
                </div>
                <button onClick={() => setStage('working')} style={{ ...btnPrimaryStyle, width: '100%' }}>
                  (Demo) Customer approved →
                </button>
              </div>
            )}

            {stage === 'working' && (
              <div>
                {/* Live timer + bar */}
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
                  <div style={{ ...mono, fontSize: 36, fontWeight: 600, color: Z.text, letterSpacing: -1, lineHeight: 1 }}>{fmtTime(secs)}</div>
                  <div style={{ fontSize: 11, color: Z.text3 }}>elapsed</div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14, marginBottom: 8 }}>
                  <span style={{ fontSize: 11, color: Z.text3 }}>Live cost · ₹{rate}/min</span>
                  <span style={{ ...mono, fontSize: 13, fontWeight: 600 }}><GradientText>{fmtINR(live)}</GradientText> <span style={{ color: Z.text3 }}>/ ₹{estimate} cap</span></span>
                </div>
                <div style={{ height: 8, borderRadius: 999, background: 'rgba(0,0,0,0.3)', overflow: 'hidden', position: 'relative' }}>
                  <div style={{
                    height: '100%', width: `${pct}%`, background: Z.gradient, borderRadius: 999,
                    transition: 'width 1s linear',
                    boxShadow: `0 0 12px ${Z.brand}`,
                  }} />
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
                  <button style={{ ...btnGhostStyle, flex: 1 }}>Pause</button>
                  <button style={{ ...btnGhostStyle, flex: 1 }}>Request extension</button>
                  <button onClick={() => setStage('complete')} style={{ ...btnPrimaryStyle, flex: 1.4 }}>Mark done</button>
                </div>
              </div>
            )}

            {stage === 'complete' && (
              <div>
                <div style={{ fontSize: 12, color: Z.text2, lineHeight: 1.5, marginBottom: 14 }}>
                  Ask the customer for their <strong style={{ color: Z.text }}>completion OTP</strong> to release payout.
                </div>
                <button onClick={() => setOtpModal({ kind: 'complete' })} style={{ ...btnPrimaryStyle, width: '100%' }}>
                  <I.lock size={14} style={{verticalAlign:'-3px', marginRight: 6}}/> Enter completion OTP
                </button>
              </div>
            )}

            {stage === 'paid' && (
              <Celebration onClose={() => nav.go('earnings')} />
            )}
          </div>
        </div>

        {/* Customer card */}
        {stage !== 'paid' && (
          <div style={{
            padding: 14, borderRadius: 16, background: 'rgba(20,8,40,0.55)',
            border: `0.5px solid ${Z.border}`, marginBottom: 12,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 42, height: 42, borderRadius: '50%',
              background: `linear-gradient(135deg, ${Z.cyan}, ${Z.brand})`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontWeight: 700, fontSize: 15,
            }}>P</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: Z.text }}>Priya M.</div>
              <div style={{ fontSize: 11, color: Z.text3 }}>{j.addr}</div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'rgba(16,185,129,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: Z.success, border: `0.5px solid rgba(16,185,129,0.3)` }}><I.phone size={16}/></div>
              <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'rgba(124,58,237,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: Z.brandLite, border: `0.5px solid ${Z.borderStrong}` }}><I.msg size={16}/></div>
            </div>
          </div>
        )}

        {/* Trust ledger */}
        {stage !== 'paid' && (
          <Glass strong style={{ padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
              <I.shield size={14} color={Z.success}/>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.4, color: Z.text2, textTransform: 'uppercase' }}>Server-verified ledger</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {STATES.slice(0, stageIdx + 1).map((s, i) => (
                <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11.5, color: Z.text2 }}>
                  <div style={{ width: 6, height: 6, borderRadius: '50%', background: i === stageIdx ? Z.brand : Z.success }} />
                  <span style={{ flex: 1 }}>{s.label}</span>
                  <span style={{ ...mono, fontSize: 10, color: Z.text4 }}>
                    {i === stageIdx ? 'live' : `7:${(15 + i).toString().padStart(2,'0')} PM`}
                  </span>
                </div>
              ))}
            </div>
          </Glass>
        )}
      </div>

      <OTPModal
        open={otpModal !== null}
        title={otpModal?.kind === 'complete' ? 'Complete job' : 'Start work'}
        sub={otpModal?.kind === 'complete'
          ? 'Customer enters this code to confirm work is done. Payout releases immediately.'
          : 'Customer shares this code so we know you\'re on-site. Inspection clock starts.'}
        onClose={() => setOtpModal(null)}
        onSuccess={() => {
          setOtpModal(null);
          if (otpModal?.kind === 'complete') setStage('paid');
          else setStage('inspecting');
        }}
      />
    </div>
  );
};

// ── Payout celebration ────────────────────────────────────────
const Celebration = ({ onClose }) => {
  const [count, setCount] = React.useState(0);
  const target = 920;
  React.useEffect(() => {
    let cur = 0;
    const id = setInterval(() => {
      cur += 28;
      if (cur >= target) { cur = target; clearInterval(id); }
      setCount(cur);
    }, 24);
    return () => clearInterval(id);
  }, []);

  return (
    <div style={{ position: 'relative', textAlign: 'center', padding: '8px 0' }}>
      {/* particles */}
      {Array.from({length: 12}).map((_, i) => {
        const a = (i/12) * Math.PI * 2;
        return (
          <div key={i} style={{
            position: 'absolute', left: '50%', top: '20%',
            width: 5, height: 5, borderRadius: '50%',
            background: i % 2 === 0 ? Z.pink : Z.cyan,
            boxShadow: '0 0 10px currentColor',
            animation: `confetti 1.6s ${i * 0.04}s ease-out`,
            '--dx': `${Math.cos(a) * 90}px`, '--dy': `${Math.sin(a) * 90}px`,
          }} />
        );
      })}
      <div style={{
        width: 64, height: 64, borderRadius: '50%', margin: '0 auto 14px',
        background: Z.gradient, display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: `0 0 50px ${Z.brand}`, color: '#fff',
      }}><I.check size={32} stroke={3}/></div>
      <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 2, color: Z.brandLite, textTransform: 'uppercase', marginBottom: 6 }}>Payout released</div>
      <div style={{ ...mono, fontSize: 48, fontWeight: 700, letterSpacing: -1.5, lineHeight: 1, marginBottom: 6 }}>
        <GradientText>{fmtINR(count)}</GradientText>
      </div>
      <div style={{ fontSize: 12, color: Z.text3, marginBottom: 20 }}>Settled to ZARVA wallet · #TXN-9241</div>
      <button onClick={onClose} style={{ ...btnPrimaryStyle, width: '100%' }}>See earnings →</button>
    </div>
  );
};

Object.assign(window, { ActiveJob, OTPModal, StateTimeline, STATES, useTicker, fmtTime, Celebration });
