// Matching radar → live tracking → OTP reveal → live billing → payment → rating
// Cinematic AI: glowing grid scans, particle systems, radar sweep

// ─── 1. MATCHING (radar + AI parse stream) ─────────────────────
const Matching = ({ nav, ticket, dir }) => {
  const d = D(dir);
  const [phase, setPhase] = React.useState(0); // 0 analyze, 1 broadcast, 2 found
  const [found, setFound] = React.useState([]);

  const candidates = [
    { id: 'w1', name: 'Vinay K.', rating: 4.94, jobs: 412, eta: 7, dist: 1.8, init: 'V', bg: '#7C3AED' },
    { id: 'w2', name: 'Suresh M.', rating: 4.88, jobs: 287, eta: 11, dist: 2.4, init: 'S', bg: '#EC4899' },
    { id: 'w3', name: 'Rakesh P.', rating: 4.91, jobs: 624, eta: 14, dist: 3.1, init: 'R', bg: '#06B6D4' },
  ];

  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase(1), 2200);
    const t2 = setTimeout(() => setFound([candidates[0]]), 3400);
    const t3 = setTimeout(() => setFound(c => [...c, candidates[1]]), 4200);
    const t4 = setTimeout(() => { setFound(candidates); setPhase(2); }, 5000);
    return () => [t1,t2,t3,t4].forEach(clearTimeout);
  }, []);

  return (
    <div style={{ height: '100%', position: 'relative', overflow: 'hidden', background: Z.bg }}>
      {/* Cancel */}
      <div onClick={() => nav.back()} style={{
        position: 'absolute', top: 60, left: 16, zIndex: 30,
        padding: '8px 14px', borderRadius: 999, fontSize: 11, fontWeight: 600,
        background: 'rgba(20,8,40,0.7)', backdropFilter: 'blur(12px)',
        border: `0.5px solid ${Z.border}`, color: Z.text2, cursor: 'pointer',
      }}>✕ Cancel</div>

      {/* Status pill */}
      <div style={{ position: 'absolute', top: 60, right: 16, zIndex: 30,
        padding: '6px 12px', borderRadius: 999, fontSize: 9.5, fontWeight: 700, letterSpacing: 1.4,
        background: 'rgba(124,58,237,0.18)', color: Z.brandLite, textTransform: 'uppercase',
        border: `0.5px solid ${Z.borderStrong}`,
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        <div style={{ width: 5, height: 5, borderRadius: '50%', background: Z.brandLite, animation: 'blink 1.2s infinite' }}/>
        {phase === 0 ? 'Analyzing' : phase === 1 ? 'Broadcasting' : 'Matched'}
      </div>

      {/* Radar / centerpiece */}
      <div style={{ position: 'absolute', top: 110, left: 0, right: 0, height: 280, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Radar phase={phase} found={found}/>
      </div>

      {/* Bottom card */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: 'linear-gradient(180deg, transparent, rgba(10,1,24,0.95) 30%)',
        padding: '60px 18px 28px', zIndex: 10,
      }}>
        {phase === 0 && (
          <div style={{ animation: 'fadeUp .3s' }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: Z.text, letterSpacing: -0.4, marginBottom: 4 }}>Reading your request</div>
            <div style={{ fontSize: 12.5, color: Z.text3, marginBottom: 18 }}>AI is parsing the problem and matching skill-level…</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                ['Category', 'Plumbing · L2 repair'],
                ['Urgency', 'Today'],
                ['Skills', 'Pipe joints, leak diagnosis'],
              ].map(([l,v], i) => (
                <div key={l} style={{
                  display: 'flex', justifyContent: 'space-between', fontSize: 12,
                  animation: `fadeUp .3s ${i*0.15}s both`,
                }}>
                  <span style={{ color: Z.text3 }}>{l}</span>
                  <span style={{ color: Z.text, fontWeight: 600 }}>{v}</span>
                </div>
              ))}
            </div>
          </div>
        )}
        {phase === 1 && (
          <div style={{ animation: 'fadeUp .3s' }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: Z.text, letterSpacing: -0.4, marginBottom: 4 }}>Finding a pro near you</div>
            <div style={{ fontSize: 12.5, color: Z.text3, marginBottom: 18 }}>23 L2 plumbers within 5 km · pinging now</div>
            {found.map((c, i) => (
              <div key={c.id} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                borderRadius: 12, marginBottom: 6,
                background: 'rgba(124,58,237,0.10)', border: `0.5px solid ${Z.borderStrong}`,
                animation: 'fadeUp .3s',
              }}>
                <div style={{ width: 30, height: 30, borderRadius: '50%', background: c.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 12 }}>{c.init}</div>
                <div style={{ flex: 1, fontSize: 12.5, color: Z.text, fontWeight: 600 }}>{c.name}</div>
                <div style={{ fontSize: 10.5, color: Z.success, display: 'flex', alignItems: 'center', gap: 4 }}>
                  <I.check size={10} stroke={3}/> accepted
                </div>
              </div>
            ))}
          </div>
        )}
        {phase === 2 && (
          <div style={{ animation: 'fadeUp .3s' }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: Z.text, letterSpacing: -0.4, marginBottom: 4 }}>3 pros available</div>
            <div style={{ fontSize: 12.5, color: Z.text3, marginBottom: 16 }}>Pick one, or we auto-assign in 8 s</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {found.map(c => (
                <div key={c.id} onClick={() => nav.go('tracking', { worker: c, ticket })} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: 12,
                  borderRadius: 14, cursor: 'pointer',
                  background: d.panel, border: `0.5px solid ${d.border}`,
                }}>
                  <div style={{ width: 44, height: 44, borderRadius: '50%', background: c.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 16 }}>{c.init}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span style={{ fontSize: 14, fontWeight: 600, color: Z.text }}>{c.name}</span>
                      <I.shield size={12} color={Z.cyan}/>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 10.5, color: Z.text3, marginTop: 2 }}>
                      <span style={{ color: Z.gold }}>★ {c.rating}</span>
                      <span>· {c.jobs} jobs</span>
                      <span>· {c.dist} km</span>
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ ...mono, fontSize: 16, fontWeight: 600, color: Z.text }}>{c.eta}m</div>
                    <div style={{ fontSize: 9.5, color: Z.text3 }}>arrival</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Radar SVG
const Radar = ({ phase, found }) => {
  const dots = [
    { x: 40, y: -60 }, { x: -70, y: 30 }, { x: 80, y: 60 },
    { x: -40, y: -50 }, { x: 90, y: -20 }, { x: -90, y: -10 },
    { x: 20, y: 80 }, { x: 60, y: -90 },
  ];
  return (
    <div style={{ position: 'relative', width: 280, height: 280 }}>
      {/* outer rings */}
      {[1,2,3,4].map(i => (
        <div key={i} style={{
          position: 'absolute', inset: `${i*8}%`, borderRadius: '50%',
          border: `0.5px solid ${i === 1 ? Z.brand : Z.borderStrong}`,
          opacity: 1 - i*0.15,
        }}/>
      ))}
      {/* sweep */}
      <div style={{
        position: 'absolute', inset: 0, borderRadius: '50%',
        background: `conic-gradient(from 0deg, transparent 0deg, ${Z.brand} 60deg, transparent 80deg)`,
        animation: 'radarSweep 2.5s linear infinite',
        opacity: 0.6,
        WebkitMaskImage: 'radial-gradient(circle, transparent 20%, black 100%)',
        maskImage: 'radial-gradient(circle, transparent 20%, black 100%)',
      }}/>
      {/* center */}
      <div style={{
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        width: 56, height: 56, borderRadius: '50%',
        background: Z.gradient, display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontWeight: 700, fontSize: 18,
        boxShadow: `0 0 30px ${Z.brand}, 0 0 60px ${Z.pink}66`,
        animation: 'pulseGlow 1.8s ease-in-out infinite',
      }}>P</div>
      {/* dots */}
      {dots.map((d, i) => (
        <div key={i} style={{
          position: 'absolute', top: '50%', left: '50%',
          transform: `translate(${d.x - 5}px, ${d.y - 5}px)`,
          width: 10, height: 10, borderRadius: '50%',
          background: found[i] ? Z.success : Z.brand,
          boxShadow: `0 0 12px ${found[i] ? Z.success : Z.brand}`,
          opacity: phase === 0 ? 0.4 : 1,
          animation: `dotPing ${1.4 + i*0.2}s ${i*0.15}s ease-in-out infinite`,
        }}/>
      ))}
      {/* grid scanlines */}
      <div style={{
        position: 'absolute', inset: 0, borderRadius: '50%',
        backgroundImage: `linear-gradient(${Z.brandLite}22 1px, transparent 1px), linear-gradient(90deg, ${Z.brandLite}22 1px, transparent 1px)`,
        backgroundSize: '20px 20px',
        WebkitMaskImage: 'radial-gradient(circle, black 30%, transparent 90%)',
        maskImage: 'radial-gradient(circle, black 30%, transparent 90%)',
      }}/>
    </div>
  );
};

// ─── 2. TRACKING (worker en route) ─────────────────────────────
const Tracking = ({ nav, worker, ticket, dir }) => {
  const d = D(dir);
  const w = worker || { name: 'Vinay K.', rating: 4.94, eta: 7, init: 'V', bg: '#7C3AED', jobs: 412 };
  const [eta, setEta] = React.useState(w.eta);
  const [showOTP, setShowOTP] = React.useState(false);

  React.useEffect(() => {
    if (eta <= 0) return;
    const t = setTimeout(() => setEta(e => e - 1), 6000);
    return () => clearTimeout(t);
  }, [eta]);

  return (
    <div style={{ height: '100%', position: 'relative', background: Z.bg }}>
      {/* Map area */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: '50%',
        background: 'radial-gradient(ellipse at 40% 60%, rgba(124,58,237,0.18), transparent 60%), #0E0824',
        overflow: 'hidden',
      }}>
        {/* Grid */}
        <div style={{
          position: 'absolute', inset: 0, opacity: 0.18,
          backgroundImage: `linear-gradient(${Z.brandLite}55 1px, transparent 1px), linear-gradient(90deg, ${Z.brandLite}55 1px, transparent 1px)`,
          backgroundSize: '36px 36px',
        }}/>
        {/* Road */}
        <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} viewBox="0 0 400 320" preserveAspectRatio="none">
          <path d="M 60 280 Q 180 230 220 160 T 340 60" stroke={Z.brand} strokeWidth="3" strokeDasharray="8 6" fill="none" opacity="0.5"/>
          <path d="M 60 280 Q 180 230 220 160" stroke={Z.brandLite} strokeWidth="3" fill="none" style={{ filter: `drop-shadow(0 0 6px ${Z.brand})` }}/>
        </svg>
        {/* Home pin */}
        <div style={{ position: 'absolute', top: '50%', left: '12%' }}>
          <div style={{ width: 36, height: 36, borderRadius: '50%', background: Z.bg, border: `2px solid ${Z.success}`, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: `0 0 20px ${Z.success}88` }}>
            <I.home size={16} color={Z.success}/>
          </div>
        </div>
        {/* Worker pin */}
        <div style={{ position: 'absolute', top: '32%', left: '52%' }}>
          <div style={{ position: 'relative' }}>
            <div style={{ position: 'absolute', top: -8, left: -8, width: 56, height: 56, borderRadius: '50%', background: Z.brand, opacity: 0.3, animation: 'pulseRing 2s infinite' }}/>
            <div style={{ width: 40, height: 40, borderRadius: '50%', background: w.bg, color: '#fff', fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', border: `2px solid #fff`, boxShadow: `0 0 20px ${Z.brand}` }}>{w.init}</div>
          </div>
        </div>
        {/* Top bar */}
        <div style={{ position: 'absolute', top: 60, left: 16, right: 16, display: 'flex', justifyContent: 'space-between' }}>
          <div onClick={() => nav.back()} style={{
            width: 38, height: 38, borderRadius: '50%', background: 'rgba(20,8,40,0.7)',
            backdropFilter: 'blur(12px)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: Z.text, cursor: 'pointer', border: `0.5px solid ${Z.border}`,
          }}><I.chevL size={20}/></div>
          <div style={{
            padding: '6px 12px', borderRadius: 999, fontSize: 9.5, fontWeight: 700, letterSpacing: 1.4,
            background: 'rgba(6,182,212,0.18)', color: '#67E8F9', textTransform: 'uppercase',
            border: `0.5px solid rgba(6,182,212,0.4)`,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <div style={{ width: 5, height: 5, borderRadius: '50%', background: Z.cyan, animation: 'blink 1.2s infinite' }}/>
            LIVE
          </div>
        </div>
      </div>

      {/* Bottom card */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, top: '46%',
        background: Z.bg, borderRadius: '24px 24px 0 0',
        padding: '20px 18px 18px', borderTop: `0.5px solid ${Z.borderStrong}`,
        boxShadow: `0 -12px 40px rgba(0,0,0,0.5)`,
        overflowY: 'auto',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}>
          <div style={{ width: 40, height: 4, borderRadius: 999, background: Z.text4 }}/>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
          <div style={{ position: 'relative' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: w.bg, color: '#fff', fontWeight: 700, fontSize: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: `0 0 20px ${Z.brand}88` }}>{w.init}</div>
            <div style={{ position: 'absolute', bottom: -2, right: -2, width: 18, height: 18, borderRadius: '50%', background: Z.success, border: `2px solid ${Z.bg}` }}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 17, fontWeight: 700, color: Z.text }}>{w.name}</span>
              <I.shield size={14} color={Z.cyan}/>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: Z.text3, marginTop: 2 }}>
              <span style={{ color: Z.gold, fontWeight: 600 }}>★ {w.rating}</span>
              <span>· {w.jobs} jobs</span>
              <span style={{ color: Z.success }}>· On the way</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <div onClick={() => nav.go('ticketChat', { worker: w })} style={{ width: 38, height: 38, borderRadius: '50%', background: 'rgba(124,58,237,0.18)', border: `0.5px solid ${Z.borderStrong}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: Z.brandLite, cursor: 'pointer' }}><I.msg size={16}/></div>
            <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'rgba(16,185,129,0.16)', border: `0.5px solid rgba(16,185,129,0.34)`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: Z.success, cursor: 'pointer' }}><I.phone size={16}/></div>
          </div>
        </div>

        {/* ETA + progress */}
        <div style={{ padding: 14, borderRadius: 16, background: d.panel, border: `0.5px solid ${d.border}`, marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
            <span style={{ ...mono, fontSize: 36, fontWeight: 600, color: Z.text, letterSpacing: -1 }}>{eta}</span>
            <span style={{ fontSize: 13, color: Z.text3 }}>min away · 1.{eta * 2 + 1} km</span>
          </div>
          <div style={{ height: 4, borderRadius: 999, background: 'rgba(0,0,0,0.3)', overflow: 'hidden' }}>
            <div style={{ width: `${Math.max(10, ((w.eta - eta) / w.eta) * 100)}%`, height: '100%', background: Z.gradient, transition: 'width .6s', boxShadow: `0 0 8px ${Z.brand}` }}/>
          </div>
        </div>

        {/* OTP reveal */}
        <div style={{
          padding: 14, borderRadius: 16, marginBottom: 14,
          background: showOTP ? 'rgba(16,185,129,0.10)' : 'rgba(245,158,11,0.08)',
          border: `1px solid ${showOTP ? 'rgba(16,185,129,0.4)' : 'rgba(245,158,11,0.34)'}`,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <I.lock size={12} color={showOTP ? Z.success : Z.gold}/>
              <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: 1.4, color: showOTP ? Z.success : Z.gold, textTransform: 'uppercase' }}>{showOTP ? 'OTP active' : 'Reveal on arrival'}</span>
            </div>
            <div onClick={() => setShowOTP(s => !s)} style={{ fontSize: 10, color: Z.text3, cursor: 'pointer' }}>{showOTP ? 'Hide' : 'Tap to reveal'}</div>
          </div>
          {showOTP ? (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ display: 'flex', gap: 6 }}>
                {['7','3','8','1'].map((n,i) => (
                  <div key={i} style={{
                    width: 46, height: 56, borderRadius: 10,
                    background: 'rgba(16,185,129,0.16)', border: `1px solid rgba(16,185,129,0.4)`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    ...mono, fontSize: 26, fontWeight: 600, color: Z.text,
                  }}>{n}</div>
                ))}
              </div>
              <div style={{ fontSize: 10.5, color: Z.text3, textAlign: 'right', maxWidth: 110, lineHeight: 1.4 }}>Share with {w.name.split(' ')[0]} <strong style={{ color: Z.text }}>only when they arrive</strong></div>
            </div>
          ) : (
            <div style={{ fontSize: 11.5, color: Z.text2, lineHeight: 1.5 }}>Your OTP unlocks when {w.name.split(' ')[0]} is at your door. Don't share it before — it's how we know the job has truly started.</div>
          )}
        </div>

        {/* Trust strip */}
        <div style={{ padding: 12, borderRadius: 12, background: 'rgba(124,58,237,0.06)', border: `0.5px solid ${Z.border}`, display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <I.shield size={16} color={Z.brandLite}/>
          <div style={{ flex: 1, fontSize: 10.5, color: Z.text2, lineHeight: 1.4 }}>If {w.name.split(' ')[0]} doesn't show by <strong style={{ color: Z.text }}>{eta + 5}:00</strong>, your job auto-reassigns. No charge.</div>
        </div>

        {/* Force-billing button (demo) */}
        <button onClick={() => nav.go('active', { worker: w, ticket })} style={{ ...btnGhostStyle, width: '100%', fontSize: 11 }}>
          → Skip to job in progress (demo)
        </button>
      </div>
    </div>
  );
};

// ─── 3. ACTIVE JOB (live billing meter) ────────────────────────
const ActiveJob = ({ nav, worker, ticket, dir }) => {
  const d = D(dir);
  const w = worker || { name: 'Vinay K.', init: 'V', bg: '#7C3AED' };
  const [secs, setSecs] = React.useState(48 * 60 + 22); // 48:22
  const [paused, setPaused] = React.useState(false);

  React.useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setSecs(s => s + 1), 1000);
    return () => clearInterval(id);
  }, [paused]);

  // Pricing: ₹150 visit + ₹6/min after 30 min
  const minutes = Math.floor(secs / 60);
  const billable = Math.max(0, minutes - 30);
  const labor = billable * 6;
  const parts = 220;
  const visit = 150;
  const total = visit + labor + parts;
  const cap = 720;
  const pct = Math.min(100, (total / cap) * 100);

  return (
    <div style={{ padding: '0 18px 120px', minHeight: '100%' }}>
      <Header nav={nav} title="Job in progress" subtitle={`#J-48217 · ${fmtTime(secs)}`}/>

      {/* Live pill */}
      <div style={{
        padding: 18, borderRadius: 22, marginBottom: 14,
        background: 'linear-gradient(160deg, rgba(16,185,129,0.18), rgba(6,182,212,0.10))',
        border: `1px solid rgba(16,185,129,0.34)`, position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ position: 'absolute', inset: 0, opacity: 0.12,
          backgroundImage: `linear-gradient(${Z.success} 1px, transparent 1px)`,
          backgroundSize: '100% 28px',
          WebkitMaskImage: 'linear-gradient(transparent, black)',
          maskImage: 'linear-gradient(transparent, black)',
        }}/>
        <div style={{ position: 'relative' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: Z.success, boxShadow: `0 0 8px ${Z.success}`, animation: 'blink 1.2s infinite' }}/>
              <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: 1.4, color: Z.success, textTransform: 'uppercase' }}>Billing live</span>
            </div>
            <div onClick={() => setPaused(p => !p)} style={{
              padding: '4px 10px', borderRadius: 999, fontSize: 10, fontWeight: 600,
              color: Z.text3, cursor: 'pointer',
              border: `0.5px solid ${Z.border}`,
            }}>{paused ? '▶ Resume' : '⏸ Pause'}</div>
          </div>
          <div style={{ ...mono, fontSize: 48, fontWeight: 600, color: Z.text, letterSpacing: -1.5, lineHeight: 1 }}>{fmtTime(secs)}</div>
          <div style={{ fontSize: 11, color: Z.text3, marginTop: 6 }}>Worker on-site · clock managed by server</div>
        </div>
      </div>

      {/* Live bill */}
      <div style={{ padding: 16, borderRadius: 18, background: d.panel, border: `0.5px solid ${d.border}`, marginBottom: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
          <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.text3, textTransform: 'uppercase' }}>Running bill</span>
          <span style={{ ...mono, fontSize: 28, fontWeight: 600, color: Z.text, letterSpacing: -0.8 }}>₹{total}</span>
        </div>
        {/* Bill line items */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
          {[
            ['Visit fee', `₹${visit}`, 'Fixed'],
            ['Labor', `₹${labor}`, `${billable} min @ ₹6/min`],
            ['Parts', `₹${parts}`, 'Pipe joint, sealant'],
          ].map(([l,v,s]) => (
            <div key={l} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: 12.5, color: Z.text, fontWeight: 500 }}>{l}</div>
                <div style={{ fontSize: 10, color: Z.text4 }}>{s}</div>
              </div>
              <div style={{ ...mono, fontSize: 13, color: Z.text, fontWeight: 600 }}>{v}</div>
            </div>
          ))}
        </div>
        {/* Cap bar */}
        <div style={{ paddingTop: 12, borderTop: `0.5px solid ${Z.border}` }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: Z.text3, marginBottom: 6 }}>
            <span>Estimate cap</span>
            <span style={{ ...mono, color: Z.text2 }}>₹{total} / ₹{cap}</span>
          </div>
          <div style={{ height: 6, borderRadius: 999, background: 'rgba(0,0,0,0.3)', overflow: 'hidden' }}>
            <div style={{ width: `${pct}%`, height: '100%', background: pct > 80 ? Z.danger : pct > 60 ? Z.gold : Z.success, transition: 'width .4s' }}/>
          </div>
          <div style={{ fontSize: 10, color: Z.text4, marginTop: 6, lineHeight: 1.5 }}>If we hit ₹{cap}, work pauses and you re-approve before continuing.</div>
        </div>
      </div>

      {/* Worker row */}
      <div style={{ padding: 12, borderRadius: 14, background: d.panel, border: `0.5px solid ${d.border}`, display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <div style={{ width: 38, height: 38, borderRadius: '50%', background: w.bg, color: '#fff', fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{w.init}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: Z.text }}>{w.name}</div>
          <div style={{ fontSize: 10.5, color: Z.success, marginTop: 1 }}>● Working</div>
        </div>
        <div onClick={() => nav.go('ticketChat', { worker: w })} style={{ width: 34, height: 34, borderRadius: '50%', background: 'rgba(124,58,237,0.18)', border: `0.5px solid ${Z.borderStrong}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: Z.brandLite, cursor: 'pointer' }}><I.msg size={15}/></div>
        <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'rgba(16,185,129,0.16)', border: `0.5px solid rgba(16,185,129,0.34)`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: Z.success, cursor: 'pointer' }}><I.phone size={15}/></div>
      </div>

      <button onClick={() => nav.go('payment', { worker: w, total })} style={{ ...btnPrimaryStyle, width: '100%', marginBottom: 8 }}>Mark complete & pay</button>
      <button onClick={() => alert('Job paused. Pro will wait for your re-approval.')} style={{ ...btnGhostStyle, width: '100%' }}>Pause job</button>
    </div>
  );
};

// ─── 4. PAYMENT ────────────────────────────────────────────────
const Payment = ({ nav, worker, total = 700, dir }) => {
  const d = D(dir);
  const w = worker || { name: 'Vinay K.', init: 'V', bg: '#7C3AED' };
  const [method, setMethod] = React.useState('upi');
  const [tip, setTip] = React.useState(0);

  return (
    <div style={{ padding: '0 18px 120px' }}>
      <Header nav={nav} title="Approve & pay" subtitle="One tap, server-locked total"/>

      {/* Final bill */}
      <div style={{ padding: 18, borderRadius: 22, marginBottom: 14,
        background: 'linear-gradient(160deg, rgba(124,58,237,0.16), rgba(236,72,153,0.08))',
        border: `1px solid ${Z.borderStrong}`,
      }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.brandLite, textTransform: 'uppercase', marginBottom: 8 }}>Total · all-in</div>
        <div style={{ ...mono, fontSize: 44, fontWeight: 600, color: Z.text, letterSpacing: -1.2, lineHeight: 1 }}>₹{total + tip}</div>
        <div style={{ fontSize: 11.5, color: Z.text3, marginTop: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
          <I.lock size={11} color={Z.success}/> Server-billed · matches your estimate
        </div>
      </div>

      {/* Bill breakdown */}
      <div style={{ padding: 14, borderRadius: 14, background: d.panel, border: `0.5px solid ${d.border}`, marginBottom: 14 }}>
        {[
          ['Visit fee', 150],
          ['Labor · 78 min', 288],
          ['Parts', 220],
          ['GST', 42],
        ].map(([l,v]) => (
          <div key={l} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 12 }}>
            <span style={{ color: Z.text3 }}>{l}</span>
            <span style={{ ...mono, color: Z.text2, fontWeight: 500 }}>₹{v}</span>
          </div>
        ))}
        {tip > 0 && (
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 12 }}>
            <span style={{ color: Z.text3 }}>Tip</span>
            <span style={{ ...mono, color: Z.success, fontWeight: 600 }}>+₹{tip}</span>
          </div>
        )}
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0 0', borderTop: `0.5px solid ${Z.border}`, marginTop: 6 }}>
          <span style={{ fontSize: 13, color: Z.text, fontWeight: 600 }}>Total</span>
          <span style={{ ...mono, fontSize: 14, color: Z.text, fontWeight: 700 }}>₹{total + tip}</span>
        </div>
      </div>

      {/* Tip worker */}
      <div style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.text3, textTransform: 'uppercase', marginBottom: 8 }}>Tip {w.name.split(' ')[0]}? (100% to them)</div>
        <div style={{ display: 'flex', gap: 6 }}>
          {[0, 20, 50, 100, 200].map(v => (
            <div key={v} onClick={() => setTip(v)} style={{
              flex: 1, padding: '10px 0', borderRadius: 10, textAlign: 'center', cursor: 'pointer',
              background: tip === v ? 'rgba(124,58,237,0.16)' : d.panel,
              border: `1px solid ${tip === v ? Z.brand : d.border}`,
              fontSize: 12, fontWeight: 600, color: tip === v ? Z.brandLite : Z.text2,
            }}>{v === 0 ? 'No' : `₹${v}`}</div>
          ))}
        </div>
      </div>

      {/* Method */}
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.text3, textTransform: 'uppercase', marginBottom: 8 }}>Pay with</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            { id: 'upi', l: 'UPI · priya@okhdfc', s: 'Recommended', tag: 'Fastest' },
            { id: 'card', l: 'HDFC •• 4421', s: 'Mastercard', tag: null },
            { id: 'cash', l: 'Cash', s: 'Pay {w.name} directly', tag: null },
          ].map(o => (
            <div key={o.id} onClick={() => setMethod(o.id)} style={{
              padding: 14, borderRadius: 14, cursor: 'pointer',
              background: method === o.id ? 'rgba(124,58,237,0.12)' : d.panel,
              border: `1px solid ${method === o.id ? Z.brand : d.border}`,
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 20, height: 20, borderRadius: '50%',
                border: `2px solid ${method === o.id ? Z.brand : Z.border}`,
                background: method === o.id ? Z.brand : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{method === o.id && <I.check size={12} color="#fff" stroke={3}/>}</div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: Z.text }}>{o.l}</span>
                  {o.tag && <Pill tone="success">{o.tag}</Pill>}
                </div>
                <div style={{ fontSize: 11, color: Z.text3, marginTop: 2 }}>{o.s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <button onClick={() => nav.go('rating', { worker: w, total: total + tip })} style={{ ...btnPrimaryStyle, width: '100%' }}>Pay ₹{total + tip} →</button>
      <button onClick={() => alert('Dispute opens chat with ZARVA support.')} style={{ ...btnGhostStyle, width: '100%', marginTop: 8 }}>Something wrong with this bill?</button>
    </div>
  );
};

// ─── 5. RATING ─────────────────────────────────────────────────
const Rating = ({ nav, worker, total = 700, dir }) => {
  const d = D(dir);
  const w = worker || { name: 'Vinay K.', init: 'V', bg: '#7C3AED' };
  const [stars, setStars] = React.useState(0);
  const [tags, setTags] = React.useState([]);
  const [done, setDone] = React.useState(false);

  const all = ['On time', 'Skilled', 'Polite', 'Clean work', 'Fair price', 'Explained well'];

  if (done) {
    return (
      <div style={{ padding: '0 18px', height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <div style={{
          width: 80, height: 80, borderRadius: '50%', background: Z.gradient,
          display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 22,
          boxShadow: `0 0 40px ${Z.brand}`,
          animation: 'pulseGlow 1.6s ease-in-out infinite',
        }}><I.check size={36} color="#fff" stroke={3}/></div>
        <div style={{ fontSize: 26, fontWeight: 700, color: Z.text, letterSpacing: -0.5 }}>Thanks, Priya</div>
        <div style={{ fontSize: 13, color: Z.text3, marginTop: 8, lineHeight: 1.5, maxWidth: 280 }}>Your job's wrapped, {w.name.split(' ')[0]}'s paid, and your rating helps others trust them.</div>
        <button onClick={() => nav.go('home')} style={{ ...btnPrimaryStyle, marginTop: 32, width: 240 }}>Back to home</button>
      </div>
    );
  }

  return (
    <div style={{ padding: '0 18px 60px' }}>
      <Header nav={nav} title="How'd it go?" subtitle="Helps us match better next time"/>

      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 28, marginTop: 10 }}>
        <div style={{ width: 80, height: 80, borderRadius: '50%', background: w.bg, color: '#fff', fontWeight: 700, fontSize: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14, boxShadow: `0 0 24px ${Z.brand}66` }}>{w.init}</div>
        <div style={{ fontSize: 19, fontWeight: 700, color: Z.text }}>{w.name}</div>
        <div style={{ fontSize: 11, color: Z.text3, marginTop: 4 }}>Plumbing · ₹{total} · 78 min</div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginBottom: 24 }}>
        {[1,2,3,4,5].map(n => (
          <div key={n} onClick={() => setStars(n)} style={{
            width: 44, height: 44, fontSize: 32, cursor: 'pointer',
            color: n <= stars ? Z.gold : Z.text4, transition: 'all .2s',
            filter: n <= stars ? `drop-shadow(0 0 6px ${Z.gold})` : 'none',
            transform: n <= stars ? 'scale(1.1)' : 'scale(1)',
          }}>★</div>
        ))}
      </div>

      {stars > 0 && (
        <div style={{ animation: 'fadeUp .3s' }}>
          <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.text3, textTransform: 'uppercase', marginBottom: 10, textAlign: 'center' }}>What was great?</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'center', marginBottom: 24 }}>
            {all.map(t => (
              <div key={t} onClick={() => setTags(s => s.includes(t) ? s.filter(x => x !== t) : [...s, t])} style={{
                padding: '8px 14px', borderRadius: 999, cursor: 'pointer', fontSize: 12, fontWeight: 600,
                background: tags.includes(t) ? 'rgba(124,58,237,0.18)' : d.panel,
                color: tags.includes(t) ? Z.brandLite : Z.text2,
                border: `0.5px solid ${tags.includes(t) ? Z.brand : d.border}`,
              }}>{t}</div>
            ))}
          </div>
          <textarea placeholder="Anything else? (optional)" rows={3} style={{
            width: '100%', padding: 12, borderRadius: 14, fontFamily: Z.font, fontSize: 13,
            background: d.panel, border: `0.5px solid ${d.border}`, color: Z.text, outline: 'none', resize: 'none', marginBottom: 22,
          }}/>
          <button onClick={() => setDone(true)} style={{ ...btnPrimaryStyle, width: '100%' }}>Submit rating</button>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { Matching, Tracking, ActiveJob, Payment, Rating, Radar });
