// goGMO dispatcher console — review / finance / return / messages views

// ── Review: 三證審查 ────────────────────────────────
function Review() {
  const [drivers, setDrivers] = React.useState(REVIEW_DRIVERS);
  const [sel, setSel] = React.useState(REVIEW_DRIVERS[0]);

  const docLabel = {
    license: '駕照',
    vehicle: '行照',
    insurance: '保險證',
  };

  const approveDriver = (id) => {
    setDrivers((prev) => prev.map((d) => (d.id === id ? { ...d, docs: { license: 'ok', vehicle: 'ok', insurance: 'ok' } } : d)));
  };

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 18 }} className="scroll-hide">
      <div style={{ display: 'grid', gridTemplateColumns: '340px 1fr', gap: 18 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {drivers.map((d) => {
            const hasIssue = Object.values(d.docs).some((v) => v !== 'ok');
            const active = sel?.id === d.id;
            return (
              <button key={d.id} onClick={() => setSel(d)} className="press" style={{
                ...cardBase, padding: 14, cursor: 'pointer', textAlign: 'left',
                borderColor: hasIssue ? C.red : active ? C.navy : C.line,
                background: active ? C.navyLight : C.white,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ width: 34, height: 34, borderRadius: '50%', background: hasIssue ? C.red : C.navy, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>{d.name[0]}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 800 }}>{d.name}</div>
                    <div style={{ fontSize: 11, color: C.ink3 }}>{d.car} · {d.plate}</div>
                  </div>
                  {hasIssue && <span style={pill({ bg: C.redLight, color: C.red })}>需補件</span>}
                </div>
                <div style={{ fontSize: 11, color: C.ink2, marginTop: 8 }}>⭐ {d.rating} · {d.trips} 趟 · {d.phone}</div>
              </button>
            );
          })}
        </div>

        <div style={cardBase}>
          {sel && (
            <>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                <div style={{ width: 44, height: 44, borderRadius: '50%', background: C.navy, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 18 }}>{sel.name[0]}</div>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 800 }}>{sel.name}</div>
                  <div style={{ fontSize: 12, color: C.ink3 }}>{sel.car} · {sel.plate} · {sel.phone}</div>
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {Object.entries(sel.docs).map(([k, v]) => {
                  const ok = v === 'ok';
                  return (
                    <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 10, background: C.bg, borderRadius: 12 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, width: 48 }}>{docLabel[k]}</div>
                      <div style={{ flex: 1, height: 54, borderRadius: 8, background: '#E9EEF4', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, color: C.ink3, border: `1px dashed ${C.line}` }}>
                        證件掃描圖示
                      </div>
                      {ok
                        ? <span style={pill({ bg: C.greenLight, color: C.green })}>✓ 有效</span>
                        : <span style={pill({ bg: C.redLight, color: C.red })}>已過期</span>}
                    </div>
                  );
                })}
              </div>
              <div style={{ marginTop: 16, display: 'flex', gap: 10 }}>
                <button onClick={() => approveDriver(sel.id)} className="press" style={{
                  flex: 1, padding: 12, border: 'none', borderRadius: 12, cursor: 'pointer',
                  background: C.navy, color: '#fff', fontWeight: 800, fontSize: 14,
                }}>全部核可，開通</button>
                <button className="press" style={{
                  flex: 1, padding: 12, border: `1px solid ${C.red}`, borderRadius: 12, cursor: 'pointer',
                  background: '#fff', color: C.red, fontWeight: 800, fontSize: 14,
                }}>要求補件</button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Finance: 帳務中心 ────────────────────────────────
function Finance() {
  const [pending, setPending] = React.useState(FINANCE_TXNS.filter((t) => t.status === 'PENDING'));
  const [transferred, setTransferred] = React.useState(FINANCE_TXNS.filter((t) => t.status === 'TRANSFERRED'));

  const markTransferred = (id) => {
    const t = pending.find((x) => x.id === id);
    if (!t) return;
    setPending((prev) => prev.filter((x) => x.id !== id));
    setTransferred((prev) => [...prev, { ...t, status: 'TRANSFERRED' }]);
  };

  const txnRow = (t, onTransfer) => (
    <div key={t.id} style={{ ...cardBase, padding: 12, display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
      <span style={pill({ bg: C.greenLight, color: C.green })}>{t.status === 'PENDING' ? '待轉帳' : '已轉帳'}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700 }}>{t.no} · {t.driver}</div>
        <div style={{ fontSize: 11, color: C.ink3 }}>平台費 ${t.fee} · 已預扣</div>
      </div>
      <div style={{ fontSize: 15, fontWeight: 800, fontFamily: C.fontMono }}>${t.amount.toLocaleString()}</div>
      {onTransfer && (
        <button onClick={() => onTransfer(t.id)} className="press" style={{
          padding: '8px 14px', border: 'none', borderRadius: 10, cursor: 'pointer',
          background: C.navy, color: '#fff', fontWeight: 700, fontSize: 12,
        }}>確認轉出</button>
      )}
    </div>
  );

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 18 }} className="scroll-hide">
      <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
        <div style={{ ...cardBase, flex: 1 }}>
          <div style={{ fontSize: 11, color: C.ink3 }}>待轉帳</div>
          <div style={{ fontSize: 24, fontWeight: 800, color: C.amber, fontFamily: C.fontMono }}>${pending.reduce((s, t) => s + t.amount, 0).toLocaleString()}</div>
        </div>
        <div style={{ ...cardBase, flex: 1 }}>
          <div style={{ fontSize: 11, color: C.ink3 }}>本月已轉</div>
          <div style={{ fontSize: 24, fontWeight: 800, color: C.green, fontFamily: C.fontMono }}>${transferred.reduce((s, t) => s + t.amount, 0).toLocaleString()}</div>
        </div>
      </div>
      <div style={cardBase}>
        <div style={{ ...sectionTitle, marginBottom: 12 }}>待轉帳列表（點確認即送出）</div>
        {pending.length === 0
          ? <div style={{ padding: 24, textAlign: 'center', fontSize: 13, color: C.ink3 }}>沒有待轉帳項目 🎉</div>
          : pending.map((t) => txnRow(t, markTransferred))}
      </div>
      <div style={{ ...cardBase, marginTop: 16 }}>
        <div style={{ ...sectionTitle, marginBottom: 12 }}>已轉帳紀錄</div>
        {transferred.map((t) => txnRow(t, null))}
      </div>
    </div>
  );
}

// ── Return: 退回重上 ────────────────────────────────
function ReturnView({ onSwitchView }) {
  const [returned, setReturned] = React.useState([
    { id: 'r1', no: '#G240810045', type: 'pickup', time: '13:00', from: '桃園機場 T2', to: '士林', price: 1350, reason: '3 小時無人接單，自動退回', editable: true },
    { id: 'r2', no: '#G240810051', type: 'charter', time: '16:30', from: '台北車站', to: '陽明山', price: 3200, reason: '派單方調整行程後退回', editable: true },
  ]);
  const [republished, setRepublished] = React.useState([]);

  const republish = (id) => {
    const r = returned.find((x) => x.id === id);
    if (!r) return;
    setReturned((prev) => prev.filter((x) => x.id !== id));
    setRepublished((prev) => [{ ...r }, ...prev]);
  };

  const card = (o, action) => (
    <div key={o.id} style={{ ...cardBase, padding: 14, marginBottom: 10, display: 'flex', alignItems: 'center', gap: 12 }}>
      <span style={pill(PILL[o.type])}>{PILL[o.type].label}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700 }}>{o.time} {o.from} → {o.to}</div>
        <div style={{ fontSize: 11, color: C.ink3 }}>{o.reason}</div>
      </div>
      <div style={{ fontSize: 14, fontWeight: 800, fontFamily: C.fontMono }}>${o.price.toLocaleString()}</div>
      {action}
    </div>
  );

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 18 }} className="scroll-hide">
      <div style={{ ...cardBase, marginBottom: 16 }}>
        <div style={{ ...sectionTitle, marginBottom: 4 }}>退回的訂單</div>
        <div style={{ fontSize: 12, color: C.ink3, marginBottom: 12 }}>編輯後重新上架，改時間、改車型、調價格都可以。</div>
        {returned.length === 0
          ? <div style={{ padding: 24, textAlign: 'center', fontSize: 13, color: C.ink3 }}>沒有退回的訂單 🎉</div>
          : returned.map((o) => card(o, (
            <button onClick={() => republish(o.id)} className="press" style={{
              padding: '8px 14px', border: 'none', borderRadius: 10, cursor: 'pointer',
              background: C.navy, color: '#fff', fontWeight: 700, fontSize: 12,
            }}>重新上架</button>
          )))}
      </div>
      <div style={cardBase}>
        <div style={{ ...sectionTitle, marginBottom: 12 }}>已重新上架</div>
        {republished.length === 0
          ? <div style={{ padding: 24, textAlign: 'center', fontSize: 13, color: C.ink3 }}>還沒有重新上架的訂單</div>
          : republished.map((o) => card(o, <span style={pill({ bg: C.greenLight, color: C.green })}>✓ 已回大廳</span>))}
      </div>
    </div>
  );
}

// ── Messages: 訊息中心 ──────────────────────────────
function Messages() {
  const [threads] = React.useState(() => {
    const byOrder = {};
    MESSAGES.forEach((m) => { if (!byOrder[m.order]) byOrder[m.order] = []; byOrder[m.order].push(m); });
    return byOrder;
  });
  const [active, setActive] = React.useState('#G240811002');

  return (
    <div style={{ flex: 1, display: 'flex', minWidth: 0 }}>
      <div style={{ width: 280, flexShrink: 0, borderRight: `1px solid ${C.line}`, background: C.white }}>
        {Object.entries(threads).map(([order, msgs]) => {
          const last = msgs[msgs.length - 1];
          const unread = msgs.some((m) => !m.me && !m.read);
          const a = active === order;
          return (
            <button key={order} onClick={() => setActive(order)} className="press" style={{
              display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer', border: 'none',
              padding: '12px 14px', borderBottom: `1px solid ${C.line}`, background: a ? C.navyLight : C.white,
              borderLeft: a ? `3px solid ${C.navy}` : '3px solid transparent',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 13, fontWeight: 800 }}>{order}</span>
                {unread && <span style={{ width: 8, height: 8, borderRadius: '50%', background: C.red }} />}
              </div>
              <div style={{ fontSize: 12, color: C.ink2, marginTop: 4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{last.name}：{last.text}</div>
            </button>
          );
        })}
      </div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, background: C.bg }}>
        <div style={{ padding: '12px 16px', background: C.white, borderBottom: `1px solid ${C.line}`, fontSize: 14, fontWeight: 800 }}>
          {active} · 訂單即時對話
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }} className="scroll-hide">
          {(threads[active] || []).map((m, i) => (
            <div key={i} style={{
              alignSelf: m.me ? 'flex-end' : 'flex-start', maxWidth: '72%',
              padding: '9px 13px', borderRadius: 14, fontSize: 13, lineHeight: 1.6,
              background: m.me ? C.navy : C.white, color: m.me ? '#fff' : C.ink,
              border: m.me ? 'none' : `1px solid ${C.line}`,
            }}>
              <div style={{ fontSize: 10, color: m.me ? 'rgba(255,255,255,.7)' : C.ink3, marginBottom: 2 }}>{m.name} · {m.time}</div>
              {m.text}
            </div>
          ))}
        </div>
        <div style={{ padding: 12, background: C.white, borderTop: `1px solid ${C.line}`, display: 'flex', gap: 8 }}>
          <input placeholder="輸入訊息…" style={{
            flex: 1, padding: '10px 14px', border: `1px solid ${C.line}`, borderRadius: 10, outline: 'none', fontSize: 13,
          }} />
          <button className="press" style={{ padding: '10px 18px', border: 'none', borderRadius: 10, background: C.navy, color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>送出</button>
        </div>
      </div>
    </div>
  );
}

window.ViewsMap = { ...window.ViewsMap, review: Review, finance: Finance, return: ReturnView, messages: Messages };

ReactDOM.render(<AppShell />, document.getElementById('root'));
