/* ============================================================
   UNIQUE Customer App — Pay, Sona AI chat, TabBar, Sheets, Toast
   ============================================================ */
const { useState: useStateP, useRef, useEffect } = React;

// ── PAY / BILLING ──────────────────────────────────────
function PayScreen({ paid, openPay, autopay, setAutopay, onBell, toast }) {
  const d = U_DATA;
  return (
    <div>
      <AppHeader sub="Billing & payments" title="Pay" onBell={onBell} />
      <div style={screenWrap}>
        <div style={{ ...card, background: 'linear-gradient(150deg,#0A2540,#061726)', border: 'none', padding: 22, color: 'var(--on-navy)' }}>
          <div style={{ fontSize: 13, color: 'var(--on-navy-soft)' }}>{paid ? 'Current balance' : `Amount due · ${d.balance.dueDate}`}</div>
          <div style={{ fontFamily: 'var(--display)', fontSize: 42, fontWeight: 800, letterSpacing: '-.03em', marginTop: 4 }}>{money(paid ? '0.00' : d.balance.due)}</div>
          <div style={{ fontSize: 12.5, color: 'var(--on-navy-soft)', marginTop: 4 }}>{paid ? 'You\u2019re all paid up. Next bill 5 Jun.' : `${d.plan.name} plan · monthly`}</div>
          <button onClick={openPay} disabled={paid} className="u-btn u-btn--primary" style={{ width: '100%', marginTop: 18, opacity: paid ? .5 : 1 }}>{paid ? 'Paid' : `Pay ${money(d.balance.due)}`}</button>
        </div>

        <div style={{ ...card, padding: 16, marginTop: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--green-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="clock" size={18} color="var(--green)" /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 600 }}>Auto-pay</div>
            <div style={{ fontSize: 12, color: 'var(--ink-faint)' }}>Charge {d.methods[0].label} on the 5th</div>
          </div>
          <div onClick={() => { setAutopay(!autopay); toast(autopay ? 'Auto-pay off' : 'Auto-pay on'); }} style={{ width: 46, height: 28, borderRadius: 99, background: autopay ? 'var(--green)' : 'var(--line-2)', position: 'relative', cursor: 'pointer', transition: 'background .2s' }}>
            <span style={{ position: 'absolute', top: 3, left: autopay ? 21 : 3, width: 22, height: 22, borderRadius: 99, background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,.2)' }} />
          </div>
        </div>

        <SectionTitle action="Add" onAction={() => toast('Add payment method')}>Payment methods</SectionTitle>
        <div style={{ ...card, overflow: 'hidden' }}>
          {d.methods.map((m, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderBottom: i < d.methods.length - 1 ? '1px solid var(--line)' : 'none' }}>
              <div style={{ width: 42, height: 30, borderRadius: 7, background: m.kind === 'wave' ? '#1DC4FF' : m.kind === 'momo' ? 'var(--red)' : 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 10, fontWeight: 800, fontFamily: 'var(--display)' }}>{m.label.slice(0,4)}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{m.label}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-faint)', fontFamily: 'var(--mono)' }}>{m.detail}</div>
              </div>
              {i === 0 && <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--green)' }}>Default</span>}
            </div>
          ))}
        </div>

        <SectionTitle action="All" onAction={() => toast('Showing all invoices')}>Recent invoices</SectionTitle>
        <div style={{ ...card, overflow: 'hidden' }}>
          {d.invoices.map((inv, i) => (
            <div key={i} onClick={() => toast(`${inv.id} — opening PDF…`)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderBottom: i < d.invoices.length - 1 ? '1px solid var(--line)' : 'none', cursor: 'pointer' }}>
              <div style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--paper-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="download" size={17} color="var(--ink)" /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{inv.month}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-faint)', fontFamily: 'var(--mono)' }}>{inv.id} · {inv.date}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 14, fontWeight: 700, fontFamily: 'var(--mono)' }}>{money(inv.amount)}</div>
                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--green)' }}>{inv.status}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── SONA AI CHAT ───────────────────────────────────────
const SONA_REPLIES = [
  { q: /slow|speed|buffer|lag/i, a: "I just ran a check on your line in Serrekunda 🛰️\n\n• Router: healthy\n• Local node: 6% congestion (normal)\n• Current: 73 Mbps down / 41 up\n\nThat's right where Surge should be. If a specific app feels slow, tell me which and I'll dig in." },
  { q: /bill|pay|invoice|charge|cost/i, a: "Your next bill is D 2,800, due 5 Jun, and auto-pay is on with Wave. Nothing's overdue. Want me to email your May invoice or turn off auto-pay?" },
  { q: /plan|upgrade|faster|apex/i, a: "You're on Surge (75 Mbps). Based on your evenings, Apex (200 Mbps, D 4,900) would give every TV its own lane. I can switch you from your next cycle — no downtime. Shall I prepare it?" },
  { q: /engineer|visit|book|technician|install/i, a: "I can book a Unique engineer. Next available slots near you:\n\n• Tomorrow, 9–11am\n• Tomorrow, 2–4pm\n• Fri, 10am–12pm\n\nWhich works? It's free on your plan." },
  { q: /outage|down|offline|no internet/i, a: "Good news — there's no outage on your node right now and your line shows Connected. If your Wi-Fi feels off, try the 'Pause & resume Wi-Fi' action on Home. Want me to restart your router remotely?" },
];
const SONA_DEFAULT = "I'm Sona, your Unique assistant. I can check your connection, explain your bill, change your plan or book an engineer — all in plain English. What's up?";

function SonaScreen({ messages, setMessages, onBell, toast }) {
  const [input, setInput] = useStateP('');
  const endRef = useRef(null);
  const [typing, setTyping] = useStateP(false);
  useEffect(() => { if (endRef.current) endRef.current.parentNode.scrollTop = endRef.current.parentNode.scrollHeight; }, [messages, typing]);

  const send = (text) => {
    const t = (text || input).trim(); if (!t) return;
    setMessages(m => [...m, { me: true, text: t }]); setInput(''); setTyping(true);
    setTimeout(() => {
      const hit = SONA_REPLIES.find(r => r.q.test(t));
      setTyping(false);
      setMessages(m => [...m, { me: false, text: hit ? hit.a : SONA_DEFAULT }]);
    }, 1100);
  };

  const chips = ['My internet is slow', 'Explain my bill', 'Upgrade my plan', 'Book an engineer'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <AppHeader sub="AI assistant · 24/7" title="Sona" onBell={onBell} />
      <div className="u-scroll" style={{ flex: 1, overflow: 'auto', padding: `4px ${PAD}px 8px`, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {messages.map((m, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: m.me ? 'flex-end' : 'flex-start' }}>
            {!m.me && <div style={{ width: 30, height: 30, borderRadius: 9, background: 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginRight: 8, flexShrink: 0, alignSelf: 'flex-end' }}><Icon name="spark" size={15} color="var(--gold)" fill="solid" /></div>}
            <div style={{ maxWidth: '78%', padding: '11px 14px', borderRadius: 16, fontSize: 14, lineHeight: 1.5, whiteSpace: 'pre-wrap', background: m.me ? 'var(--ink)' : 'var(--card)', color: m.me ? 'var(--paper)' : 'var(--ink)', border: m.me ? 'none' : '1px solid var(--line)', borderBottomRightRadius: m.me ? 5 : 16, borderBottomLeftRadius: m.me ? 16 : 5, boxShadow: 'var(--shadow-sm)' }}>{m.text}</div>
          </div>
        ))}
        {typing && (
          <div style={{ display: 'flex', alignItems: 'flex-end' }}>
            <div style={{ width: 30, height: 30, borderRadius: 9, background: 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginRight: 8 }}><Icon name="spark" size={15} color="var(--gold)" fill="solid" /></div>
            <div style={{ padding: '13px 16px', borderRadius: 16, borderBottomLeftRadius: 5, background: 'var(--card)', border: '1px solid var(--line)', display: 'flex', gap: 4 }}>
              {[0,1,2].map(i => <span key={i} style={{ width: 6, height: 6, borderRadius: 99, background: 'var(--ink-faint)', animation: `u-pulse 1.2s ${i*0.2}s infinite` }} />)}
            </div>
          </div>
        )}
        <div ref={endRef} />
      </div>
      <div style={{ padding: `6px ${PAD}px 10px`, background: 'var(--paper)' }}>
        <div className="u-scroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 8 }}>
          {chips.map((c, i) => <button key={i} onClick={() => send(c)} style={{ whiteSpace: 'nowrap', flexShrink: 0, padding: '8px 13px', borderRadius: 99, border: '1px solid var(--line-2)', background: 'var(--card)', fontSize: 12.5, fontWeight: 600, color: 'var(--ink-soft)', cursor: 'pointer', fontFamily: 'var(--sans)' }}>{c}</button>)}
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder="Message Sona…" style={{ flex: 1, padding: '13px 16px', borderRadius: 99, border: '1px solid var(--line-2)', background: 'var(--card)', fontSize: 14.5, fontFamily: 'var(--sans)', outline: 'none', color: 'var(--ink)' }} />
          <button onClick={() => send()} style={{ width: 46, height: 46, borderRadius: 99, border: 'none', background: 'var(--red)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}><Icon name="send" size={20} color="#fff" fill="solid" /></button>
        </div>
      </div>
    </div>
  );
}

// ── TAB BAR ────────────────────────────────────────────
function TabBar({ active, go }) {
  const tabs = [['home', 'Home'], ['usage', 'Usage'], ['pay', 'Pay'], ['sona', 'Sona'], ['account', 'Account']];
  return (
    <div style={{ flexShrink: 0, paddingBottom: 'var(--tabpad, 24px)', paddingTop: 8, background: 'rgba(250,250,247,.94)', backdropFilter: 'blur(14px)', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-around' }}>
      {tabs.map(([id, label]) => {
        const on = active === id;
        return (
          <button key={id} onClick={() => go(id)} style={{ background: 'none', border: 'none', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, cursor: 'pointer', flex: 1, padding: '2px 0' }}>
            {id === 'sona'
              ? <div style={{ width: 26, height: 26, borderRadius: 8, background: on ? 'var(--red)' : 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="spark" size={15} color={on ? '#fff' : 'var(--gold)'} fill="solid" /></div>
              : <Icon name={id} size={23} color={on ? 'var(--red)' : 'var(--ink-faint)'} sw={on ? 2.4 : 2} />}
            <span style={{ fontSize: 10.5, fontWeight: on ? 700 : 600, color: on ? 'var(--red)' : 'var(--ink-faint)' }}>{label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ── PAY SHEET (flow) ───────────────────────────────────
function PaySheet({ open, onClose, onPaid }) {
  const [stage, setStage] = useStateP('select'); // select | processing | done
  const [method, setMethod] = useStateP(U_DATA.methods[0]);
  useEffect(() => { if (open) setStage('select'); }, [open]);
  const pay = () => { setStage('processing'); setTimeout(() => setStage('done'), 1700); };
  return (
    <Sheet open={open} onClose={onClose} title={stage === 'done' ? null : 'Pay your bill'}>
      {stage === 'select' && (
        <div>
          <div style={{ ...card, padding: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <span style={{ color: 'var(--ink-soft)', fontSize: 14 }}>Amount due</span>
            <span style={{ fontFamily: 'var(--display)', fontSize: 26, fontWeight: 800 }}>{money(U_DATA.balance.due)}</span>
          </div>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink-faint)', margin: '4px 2px 10px' }}>Pay with</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {U_DATA.methods.map((m, i) => (
              <button key={i} onClick={() => setMethod(m)} style={{ ...card, border: method.id === m.id ? '2px solid var(--red)' : '1px solid var(--line)', padding: 14, display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer', textAlign: 'left' }}>
                <div style={{ width: 42, height: 30, borderRadius: 7, background: m.kind === 'wave' ? '#1DC4FF' : m.kind === 'momo' ? 'var(--red)' : 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 10, fontWeight: 800, fontFamily: 'var(--display)' }}>{m.label.slice(0,4)}</div>
                <div style={{ flex: 1 }}><div style={{ fontSize: 14.5, fontWeight: 600 }}>{m.label}</div><div style={{ fontSize: 12, color: 'var(--ink-faint)', fontFamily: 'var(--mono)' }}>{m.detail}</div></div>
                {method.id === m.id && <Icon name="check" size={20} color="var(--red)" />}
              </button>
            ))}
          </div>
          <button onClick={pay} className="u-btn u-btn--primary" style={{ width: '100%', marginTop: 18 }}>Pay {money(U_DATA.balance.due)}</button>
        </div>
      )}
      {stage === 'processing' && (
        <div style={{ padding: '40px 0', textAlign: 'center' }}>
          <div style={{ width: 54, height: 54, borderRadius: 99, border: '4px solid var(--paper-3)', borderTopColor: 'var(--red)', margin: '0 auto', animation: 'u-spin .8s linear infinite' }} />
          <div style={{ marginTop: 18, fontSize: 15, fontWeight: 600 }}>Processing with {method.label}…</div>
        </div>
      )}
      {stage === 'done' && (
        <div style={{ padding: '24px 0 8px', textAlign: 'center' }}>
          <div style={{ width: 70, height: 70, borderRadius: 99, background: 'var(--green-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto', animation: 'u-pop .4s' }}><Icon name="check" size={38} color="var(--green)" sw={2.6} /></div>
          <div style={{ fontFamily: 'var(--display)', fontSize: 24, fontWeight: 700, marginTop: 16 }}>Payment received</div>
          <div style={{ fontSize: 14, color: 'var(--ink-soft)', marginTop: 6 }}>{money(U_DATA.balance.due)} paid with {method.label}. A receipt is on its way.</div>
          <button onClick={() => { onPaid(); onClose(); }} className="u-btn u-btn--ink" style={{ width: '100%', marginTop: 22 }}>Done</button>
        </div>
      )}
    </Sheet>
  );
}

// ── PLAN SHEET ─────────────────────────────────────────
function PlanSheet({ open, onClose, plan, setPlan, toast }) {
  const [sel, setSel] = useStateP(plan.name);
  useEffect(() => { if (open) setSel(plan.name); }, [open, plan]);
  return (
    <Sheet open={open} onClose={onClose} title="Change your plan">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {U_DATA.plans.map((p, i) => (
          <button key={i} onClick={() => setSel(p.name)} style={{ ...card, border: sel === p.name ? '2px solid var(--red)' : '1px solid var(--line)', padding: 16, display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer', textAlign: 'left' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--display)', fontSize: 19, fontWeight: 700 }}>{p.name} · {p.speed} Mbps</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-faint)' }}>{p.tag} · {money(p.price)}/mo</div>
            </div>
            {p.name === plan.name && <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--green)', background: 'var(--green-soft)', padding: '4px 9px', borderRadius: 99 }}>Current</span>}
            {sel === p.name && p.name !== plan.name && <Icon name="check" size={22} color="var(--red)" />}
          </button>
        ))}
      </div>
      <button onClick={() => { const np = U_DATA.plans.find(p => p.name === sel); setPlan(np); onClose(); toast(sel === plan.name ? 'No change made' : `Switched to ${sel} — live next cycle`); }} className="u-btn u-btn--primary" style={{ width: '100%', marginTop: 18 }}>{sel === plan.name ? 'Keep current plan' : `Switch to ${sel}`}</button>
      <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-faint)', marginTop: 12 }}>Changes apply from your next billing cycle. No downtime.</div>
    </Sheet>
  );
}

// ── SPEED TEST SHEET ───────────────────────────────────
function SpeedSheet({ open, onClose }) {
  const [val, setVal] = useStateP(0);
  const [done, setDone] = useStateP(false);
  useEffect(() => {
    if (!open) return; setVal(0); setDone(false);
    let v = 0; const id = setInterval(() => { v += Math.random() * 9; if (v >= 73.4) { v = 73.4; clearInterval(id); setDone(true); } setVal(v); }, 80);
    return () => clearInterval(id);
  }, [open]);
  return (
    <Sheet open={open} onClose={onClose} title="Speed test">
      <div style={{ textAlign: 'center', padding: '10px 0 8px' }}>
        <Ring pct={Math.min(100, (val / 100) * 100)} size={180} sw={16} color="var(--red)">
          <span style={{ fontFamily: 'var(--display)', fontSize: 46, fontWeight: 800 }}>{val.toFixed(1)}</span>
          <span style={{ fontSize: 13, color: 'var(--ink-faint)' }}>Mbps down</span>
        </Ring>
        <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
          {[['Upload', done ? '41.2' : '—', 'Mbps'], ['Ping', done ? '12' : '—', 'ms'], ['Jitter', done ? '3' : '—', 'ms']].map((m, i) => (
            <div key={i} style={{ ...card, flex: 1, padding: '12px 8px' }}>
              <div style={{ fontSize: 11, color: 'var(--ink-faint)' }}>{m[0]}</div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 17, fontWeight: 600, marginTop: 3 }}>{m[1]}</div>
            </div>
          ))}
        </div>
        {done && <div style={{ marginTop: 16, fontSize: 13.5, color: 'var(--green)', fontWeight: 700 }}>✓ Excellent — right on target for Surge</div>}
      </div>
    </Sheet>
  );
}

// ── TOAST ──────────────────────────────────────────────
function Toast({ msg }) {
  if (!msg) return null;
  return (
    <div style={{ position: 'absolute', bottom: 96, left: '50%', transform: 'translateX(-50%)', zIndex: 90, background: 'var(--ink)', color: 'var(--paper)', padding: '12px 20px', borderRadius: 99, fontSize: 13.5, fontWeight: 600, boxShadow: 'var(--shadow-lg)', animation: 'u-pop .25s', whiteSpace: 'nowrap', maxWidth: '90%' }}>{msg}</div>
  );
}

Object.assign(window, { PayScreen, SonaScreen, TabBar, PaySheet, PlanSheet, SpeedSheet, Toast, SONA_DEFAULT });
