// Customer chat, orders/history, profile screens

// ─── CHAT (with worker, during/after job) ───────────────────────
const TicketChatWorker = ({ nav, worker, dir }) => {
  const d = D(dir);
  const w = worker || { name: 'Vinay K.', init: 'V', bg: '#7C3AED', rating: 4.94 };
  const [msgs, setMsgs] = React.useState([
    { from: 'sys', text: 'Vinay accepted your job · 6:42 PM' },
    { from: 'w', text: "Hi! On my way, ETA 7 min. Carrying my full kit." , t: '6:43' },
    { from: 'me', text: "Great, thanks! It's the kitchen sink, leak under counter.", t: '6:43' },
    { from: 'w', text: "Got it. Could you send a photo of where it's coming from?", t: '6:44' },
    { from: 'me', text: '[photo]', img: true, t: '6:45' },
    { from: 'w', text: "Thanks. Looks like a joint issue. I have the parts.", t: '6:46' },
    { from: 'sys', text: 'OTP unlocked · Vinay arrived' },
  ]);
  const [draft, setDraft] = React.useState('');
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs]);

  const send = () => {
    if (!draft.trim()) return;
    setMsgs(m => [...m, { from: 'me', text: draft, t: 'now' }]);
    setDraft('');
    setTimeout(() => {
      setMsgs(m => [...m, { from: 'w', text: "Got it, will check on that.", t: 'now' }]);
    }, 900);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Header */}
      <div style={{
        padding: '60px 16px 12px', display: 'flex', alignItems: 'center', gap: 10,
        borderBottom: `0.5px solid ${Z.border}`, background: 'rgba(10,1,24,0.85)',
        backdropFilter: 'blur(12px)', zIndex: 5,
      }}>
        <div onClick={() => nav.back()} style={{
          width: 36, height: 36, 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={18}/></div>
        <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={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: Z.text }}>{w.name}</span>
            <I.shield size={11} color={Z.cyan}/>
          </div>
          <div style={{ fontSize: 10.5, color: Z.success, marginTop: 1 }}>● On site · L2 plumber</div>
        </div>
        <div style={{ width: 36, height: 36, 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>

      {/* Pinned ticket */}
      <div style={{ padding: '10px 14px', background: 'rgba(124,58,237,0.10)', border: `0.5px solid ${Z.borderStrong}`, margin: 12, borderRadius: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
        <I.briefcase size={14} color={Z.brandLite}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11.5, color: Z.text, fontWeight: 600 }}>Plumbing · Leak repair</div>
          <div style={{ ...mono, fontSize: 10, color: Z.text3 }}>#J-48217 · ₹450–₹720</div>
        </div>
        <div style={{ fontSize: 10, color: Z.success, fontWeight: 600 }}>● Active</div>
      </div>

      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '4px 14px 14px' }}>
        {msgs.map((m, i) => {
          if (m.from === 'sys') return (
            <div key={i} style={{ textAlign: 'center', margin: '12px 0', fontSize: 10.5, color: Z.text4 }}>· {m.text} ·</div>
          );
          const me = m.from === 'me';
          return (
            <div key={i} style={{ display: 'flex', justifyContent: me ? 'flex-end' : 'flex-start', marginBottom: 8 }}>
              <div style={{ maxWidth: '76%' }}>
                {m.img ? (
                  <div style={{ width: 160, height: 100, borderRadius: 14, background: `linear-gradient(135deg, ${Z.brandDeep}, ${Z.bgSurface})`, border: `0.5px solid ${Z.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 32 }}>📷</div>
                ) : (
                  <div style={{
                    padding: '8px 12px', borderRadius: 14, fontSize: 13, lineHeight: 1.4,
                    background: me ? Z.gradient : d.panel,
                    color: Z.text, border: me ? 'none' : `0.5px solid ${d.border}`,
                  }}>{m.text}</div>
                )}
                <div style={{ fontSize: 9.5, color: Z.text4, marginTop: 2, textAlign: me ? 'right' : 'left' }}>{m.t}</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Quick replies */}
      <div style={{ padding: '0 14px 8px', display: 'flex', gap: 6, overflowX: 'auto' }} className="scroll-x">
        {['On my way', 'Door is open', 'Will be there in 5'].map(q => (
          <div key={q} onClick={() => setDraft(q)} style={{
            whiteSpace: 'nowrap', padding: '6px 12px', borderRadius: 999, fontSize: 11, fontWeight: 600,
            background: 'rgba(124,58,237,0.12)', color: Z.brandLite,
            border: `0.5px solid rgba(124,58,237,0.3)`, cursor: 'pointer',
          }}>{q}</div>
        ))}
      </div>

      {/* Input */}
      <div style={{
        padding: '10px 14px 16px', borderTop: `0.5px solid ${Z.border}`,
        background: 'rgba(10,1,24,0.85)', backdropFilter: 'blur(12px)',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'rgba(124,58,237,0.16)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: Z.brandLite, border: `0.5px solid ${Z.borderStrong}`, cursor: 'pointer' }}><I.plus size={16}/></div>
        <input value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder="Message Vinay…" style={{
          flex: 1, padding: '10px 14px', borderRadius: 999, fontSize: 13.5, fontFamily: Z.font,
          background: d.panel, border: `0.5px solid ${d.border}`, color: Z.text, outline: 'none',
        }}/>
        <div onClick={send} style={{ width: 38, height: 38, borderRadius: '50%', background: Z.gradient, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', cursor: 'pointer', boxShadow: `0 0 12px ${Z.brand}88` }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m22 2-7 20-4-9-9-4 20-7z"/></svg>
        </div>
      </div>
    </div>
  );
};

// ─── ORDERS (active + history) ────────────────────────────────
const COrders = ({ nav, dir }) => {
  const d = D(dir);
  const [tab, setTab] = React.useState('active');

  const active = [
    { id: 'J-48217', svc: 'Plumbing', stage: 'In progress', worker: 'Vinay K.', when: 'Now', total: '₹450–720', tone: Z.success, init: 'V', bg: '#7C3AED' },
  ];
  const history = [
    { id: 'J-47998', svc: 'AC service', stage: 'Completed', worker: 'Suresh M.', when: 'Yesterday', total: '₹680', tone: Z.text2, rating: 5, init: 'S', bg: '#EC4899' },
    { id: 'J-47651', svc: 'Deep clean', stage: 'Completed', worker: 'Lakshmi R.', when: 'Mar 14', total: '₹1,200', tone: Z.text2, rating: 5, init: 'L', bg: '#06B6D4' },
    { id: 'J-46802', svc: 'Electrical', stage: 'Completed', worker: 'Rakesh P.', when: 'Mar 02', total: '₹520', tone: Z.text2, rating: 4, init: 'R', bg: '#10B981' },
    { id: 'J-46412', svc: 'Carpentry', stage: 'Cancelled', worker: 'Anand M.', when: 'Feb 22', total: '₹0 (refunded)', tone: Z.danger, init: 'A', bg: '#F59E0B' },
    { id: 'J-45988', svc: 'Painting', stage: 'Completed', worker: 'Team of 2', when: 'Feb 10', total: '₹4,800', tone: Z.text2, rating: 5, init: '2', bg: '#7C3AED' },
  ];

  const list = tab === 'active' ? active : history;

  return (
    <div style={{ padding: '0 18px 120px' }}>
      <div style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 11, color: Z.text3, fontWeight: 500, marginBottom: 2 }}>Your jobs</div>
        <div style={{ fontSize: 26, fontWeight: 700, color: Z.text, letterSpacing: -0.6 }}>Orders</div>
      </div>

      <div style={{ display: 'flex', gap: 6, marginBottom: 18, padding: 4, borderRadius: 12, background: d.panel, border: `0.5px solid ${d.border}` }}>
        {['active', 'history'].map(t => (
          <div key={t} onClick={() => setTab(t)} style={{
            flex: 1, textAlign: 'center', padding: '9px 0', borderRadius: 10, cursor: 'pointer',
            background: tab === t ? Z.gradient : 'transparent',
            color: tab === t ? '#fff' : Z.text3, fontSize: 12, fontWeight: 600,
            boxShadow: tab === t ? `0 4px 12px ${Z.brand}44` : 'none',
            textTransform: 'capitalize',
          }}>{t}{t === 'active' && active.length > 0 && ` · ${active.length}`}</div>
        ))}
      </div>

      {list.length === 0 && (
        <div style={{ padding: 40, textAlign: 'center', color: Z.text3 }}>
          <div style={{ fontSize: 32, marginBottom: 10, opacity: 0.4 }}>📭</div>
          <div style={{ fontSize: 13 }}>Nothing here yet.</div>
        </div>
      )}

      {list.map(j => (
        <div key={j.id} onClick={() => nav.go(tab === 'active' ? 'active' : 'orderDetail', { ticket: j })} style={{
          padding: 14, borderRadius: 16, marginBottom: 10, cursor: 'pointer',
          background: d.panel, border: `0.5px solid ${d.border}`, position: 'relative',
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 10 }}>
            <div style={{ width: 40, height: 40, borderRadius: 12, background: j.bg, color: '#fff', fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{j.init}</div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: Z.text }}>{j.svc}</div>
                <div style={{ ...mono, fontSize: 13, fontWeight: 700, color: Z.text }}>{j.total}</div>
              </div>
              <div style={{ fontSize: 11.5, color: Z.text3, marginTop: 2 }}>{j.worker} · {j.when}</div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 10, borderTop: `0.5px solid ${Z.border}` }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: j.tone, boxShadow: tab === 'active' ? `0 0 8px ${j.tone}` : 'none', animation: tab === 'active' ? 'blink 1.4s infinite' : 'none' }}/>
              <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: 1, color: j.tone, textTransform: 'uppercase' }}>{j.stage}</span>
            </div>
            {j.rating && <div style={{ fontSize: 11, color: Z.gold }}>{'★'.repeat(j.rating)}<span style={{ color: Z.text4 }}>{'★'.repeat(5 - j.rating)}</span></div>}
            <div style={{ ...mono, fontSize: 10, color: Z.text4 }}>#{j.id}</div>
          </div>
        </div>
      ))}
    </div>
  );
};

// ─── PROFILE ─────────────────────────────────────────────────
const CProfile = ({ nav, dir, onDirChange }) => {
  const d = D(dir);
  return (
    <div style={{ padding: '0 18px 120px' }}>
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 11, color: Z.text3, fontWeight: 500, marginBottom: 2 }}>Account</div>
        <div style={{ fontSize: 26, fontWeight: 700, color: Z.text, letterSpacing: -0.6 }}>Profile</div>
      </div>

      {/* Identity card */}
      <div style={{
        padding: 18, borderRadius: 22, marginBottom: 18, position: 'relative', overflow: 'hidden',
        background: 'linear-gradient(160deg, rgba(124,58,237,0.24), rgba(236,72,153,0.12))',
        border: `1px solid ${Z.borderStrong}`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 60, height: 60, borderRadius: '50%', background: Z.gradient, color: '#fff', fontWeight: 700, fontSize: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: `0 0 20px ${Z.brand}66` }}>P</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 17, fontWeight: 700, color: Z.text }}>Priya Sharma</div>
            <div style={{ fontSize: 11, color: Z.text3, marginTop: 2 }}>+91 98••• ••421 · since Aug '24</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
              <Pill tone="brand">★ Trusted</Pill>
              <Pill tone="success">23 jobs</Pill>
            </div>
          </div>
        </div>
      </div>

      {/* Quick stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 22 }}>
        {[
          { v: '23', l: 'Jobs', c: Z.text },
          { v: '₹18,420', l: 'Saved vs. street', c: Z.success },
          { v: '4.9★', l: 'You give', c: Z.gold },
        ].map(s => (
          <div key={s.l} style={{ padding: 14, borderRadius: 14, background: d.panel, border: `0.5px solid ${d.border}`, textAlign: 'center' }}>
            <div style={{ ...mono, fontSize: 18, fontWeight: 700, color: s.c, letterSpacing: -0.5 }}>{s.v}</div>
            <div style={{ fontSize: 10, color: Z.text3, marginTop: 4 }}>{s.l}</div>
          </div>
        ))}
      </div>

      {/* Sections */}
      <Section title="Trust & safety">
        <Row icon="🛡" label="Verified addresses" detail="2 saved" onClick={() => nav.go('addresses')}/>
        <Row icon="💳" label="Payment methods" detail="UPI · HDFC card" onClick={() => {}}/>
        <Row icon="📜" label="Dispute history" detail="0 open" onClick={() => {}}/>
        <Row icon="🔐" label="Privacy & data" onClick={() => {}}/>
      </Section>

      <Section title="App">
        <Row icon="🔔" label="Notifications" toggle/>
        <Row icon="🌐" label="Language" detail="English"/>
        <Row icon="📍" label="Default address" detail="Home"/>
        <Row icon="🎁" label="Refer a friend" detail="₹100 each" pulse/>
      </Section>

      {/* Direction switcher (in-product) */}
      <Section title="Design direction (demo)">
        <div style={{ padding: '8px 14px 12px', display: 'flex', flexDirection: 'column', gap: 6 }}>
          {[
            { id: 'cinematic', l: 'Cinematic', s: 'Neon, radar, motion' },
            { id: 'calm', l: 'Calm', s: 'Lavender, roomy, gentle' },
            { id: 'expert', l: 'Expert', s: 'Dense, ledger, precise' },
          ].map(o => (
            <div key={o.id} onClick={() => onDirChange?.(o.id)} style={{
              padding: 12, borderRadius: 12, cursor: 'pointer',
              background: dir === o.id ? 'rgba(124,58,237,0.16)' : 'transparent',
              border: `0.5px solid ${dir === o.id ? Z.brand : Z.border}`,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <div style={{
                width: 18, height: 18, borderRadius: '50%',
                border: `2px solid ${dir === o.id ? Z.brand : Z.border}`,
                background: dir === o.id ? Z.brand : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{dir === o.id && <I.check size={10} color="#fff" stroke={3}/>}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: Z.text }}>{o.l}</div>
                <div style={{ fontSize: 10, color: Z.text3 }}>{o.s}</div>
              </div>
            </div>
          ))}
        </div>
      </Section>

      <div style={{ padding: '14px 0', textAlign: 'center', fontSize: 10.5, color: Z.text4 }}>
        ZARVA · v2.4.1 · Made for India
      </div>
    </div>
  );
};

const Section = ({ title, children }) => (
  <div style={{ marginBottom: 20 }}>
    <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: Z.text3, textTransform: 'uppercase', marginBottom: 8, paddingLeft: 4 }}>{title}</div>
    <div style={{ borderRadius: 16, background: D('cinematic').panel, border: `0.5px solid ${Z.border}`, overflow: 'hidden' }}>{children}</div>
  </div>
);

const Row = ({ icon, label, detail, onClick, toggle, pulse }) => {
  const [on, setOn] = React.useState(true);
  return (
    <div onClick={onClick} style={{
      padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12, cursor: onClick ? 'pointer' : 'default',
      borderBottom: `0.5px solid ${Z.border}`, position: 'relative',
    }}>
      <div style={{ width: 32, height: 32, borderRadius: 10, background: 'rgba(124,58,237,0.10)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>{icon}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: Z.text }}>{label}</div>
      </div>
      {detail && <div style={{ fontSize: 11, color: Z.text3 }}>{detail}</div>}
      {toggle ? (
        <div onClick={(e) => { e.stopPropagation(); setOn(o => !o); }} style={{
          width: 38, height: 22, borderRadius: 999, background: on ? Z.brand : Z.text4,
          padding: 2, transition: 'all .2s', cursor: 'pointer',
        }}>
          <div style={{
            width: 18, height: 18, borderRadius: '50%', background: '#fff',
            transform: on ? 'translateX(16px)' : 'translateX(0)', transition: 'all .2s',
          }}/>
        </div>
      ) : onClick ? <I.chevR size={14} color={Z.text3}/> : null}
      {pulse && <div style={{ position: 'absolute', top: 14, right: 36, width: 7, height: 7, borderRadius: '50%', background: Z.pink, boxShadow: `0 0 8px ${Z.pink}` }}/>}
    </div>
  );
};

Object.assign(window, { TicketChatWorker, COrders, CProfile, Section, Row });
