// goGMO dispatcher console — shell + dashboard + AI parse

const VIEW_NAV = [
  { key: 'dashboard', label: '行控中心', icon: '▦' },
  { key: 'ai', label: 'AI 解析', icon: '✦' },
  { key: 'review', label: '司機審核', icon: '✧' },
  { key: 'finance', label: '帳務中心', icon: '¥' },
  { key: 'return', label: '退回重上', icon: '↺' },
  { key: 'messages', label: '訊息中心', icon: '✉' },
];

const cardBase = {
  background: C.white, border: `1px solid ${C.line}`, borderRadius: 14, padding: 18,
  boxShadow: '0 1px 2px rgba(15,23,33,.03)',
};

const pill = (s) => ({
  display: 'inline-flex', alignItems: 'center', gap: 6,
  fontSize: 11, fontWeight: 700, padding: '3px 10px', borderRadius: 999, whiteSpace: 'nowrap',
  background: s.bg, color: s.color,
});

const sectionTitle = { fontSize: 15, fontWeight: 800, color: C.ink, marginBottom: 4 };

function App() {
  const initialView = typeof window !== 'undefined'
    ? (new URLSearchParams(window.location.search).get('v') || 'dashboard')
    : 'dashboard';
  const [view, setView] = React.useState(initialView);
  const [selectedOrder, setSelectedOrder] = React.useState(ORDERS[0]);
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== 'undefined' && window.innerWidth < 560
  );

  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 560px)');
    const onC = (e) => setIsMobile(e.matches);
    mq.addEventListener('change', onC);
    setIsMobile(mq.matches);
    return () => mq.removeEventListener('change', onC);
  }, []);

  const switchView = (k) => setView(k);

  const ViewComponent = window.ViewsMap[view];
  return (
    <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', height: '100%', background: C.bg, overflow: 'hidden' }}>
      {/* Sidebar: left rail on desktop, bottom nav on mobile */}
      <div style={{
        display: 'flex',
        flexDirection: isMobile ? 'row' : 'column',
        background: C.navyDeep,
        flexShrink: 0,
        ...(isMobile
          ? { height: 60, order: 2 }
          : { width: 64, order: 0, height: '100%' }),
      }}>
        {!isMobile && (
          <div style={{
            height: 56, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 22, fontWeight: 900, color: C.gold,
          }}>G</div>
        )}
        <div style={{
          flex: 1,
          display: 'flex',
          ...(isMobile ? { flexDirection: 'row', justifyContent: 'space-around' } : { flexDirection: 'column', gap: 4, padding: '8px 0' }),
        }}>
          {VIEW_NAV.map((n) => {
            const active = view === n.key;
            return (
              <button key={n.key} onClick={() => switchView(n.key)} className="press"
                style={{
                  cursor: 'pointer',
                  border: 'none',
                  background: active ? 'rgba(255,255,255,.12)' : 'transparent',
                  color: active ? C.gold : 'rgba(255,255,255,.45)',
                  display: 'flex',
                  ...(isMobile
                    ? { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2, padding: '6px 8px' }
                    : { flexDirection: 'column', alignItems: 'center', gap: 3, padding: '10px 0', borderLeft: active ? `3px solid ${C.gold}` : '3px solid transparent' }),
                }}>
                <span style={{ fontSize: isMobile ? 15 : 17, fontWeight: 700 }}>{n.icon}</span>
                <span style={{ fontSize: isMobile ? 9 : 9, fontWeight: 700 }}>{n.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Main */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, ...(isMobile ? { order: 1 } : {}) }}>
        <div style={{
          height: 56, background: C.white, borderBottom: `1px solid ${C.line}`,
          display: 'flex', alignItems: 'center', padding: '0 20px', gap: 14, flexShrink: 0,
        }}>
          <div style={sectionTitle}>{VIEW_NAV.find((n) => n.key === view)?.label}</div>
          <span style={{ ...pill(STATUS_STYLE.IN_PROGRESS), fontSize: 10 }}>
            <span className="live-dot" />即時同步中
          </span>
          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 10 }}>
            {!isMobile && <span style={{ fontSize: 12, color: C.ink3 }}>美好車行 · 陳經理</span>}
            <div style={{
              width: 30, height: 30, borderRadius: '50%', background: C.navy, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700,
            }}>陳</div>
          </div>
        </div>

        <div style={{ flex: 1, overflow: 'hidden', display: 'flex' }}>
          {ViewComponent ? <ViewComponent
            selectedOrder={selectedOrder}
            onSelectOrder={setSelectedOrder}
            onSwitchView={switchView}
          /> : null}
        </div>
      </div>
    </div>
  );
}

// ── Dashboard: 行控中心（對齊實際後台布局）────────────
function Dashboard({ selectedOrder, onSelectOrder, onSwitchView }) {
  const [isNarrow, setIsNarrow] = React.useState(
    typeof window !== 'undefined' && window.innerWidth < 720
  );
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 720px)');
    const onC = (e) => setIsNarrow(e.matches);
    mq.addEventListener('change', onC);
    setIsNarrow(mq.matches);
    return () => mq.removeEventListener('change', onC);
  }, []);

  const statRow = [
    { label: '已派出', value: 4, color: C.navy },
    { label: '進行中', value: 2, color: C.green },
    { label: '即將到期', value: 1, color: C.amber },
    { label: '未派出', value: 1, color: C.red },
  ];
  const alertCards = [
    { label: '未派出', count: 1, danger: true },
    { label: '即將到期', count: 1, active: true },
    { label: '待審核', count: 2, active: false },
    { label: '轉單', count: 0, active: false },
  ];

  return (
    <div style={{ display: 'flex', flex: 1, minWidth: 0 }}>
      {/* Left: order list */}
      {!isNarrow && (
      <div style={{ width: 360, flexShrink: 0, borderRight: `1px solid ${C.line}`, background: C.white, display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '14px 16px', borderBottom: `1px solid ${C.line}` }}>
          <div style={{ fontSize: 16, fontWeight: 800 }}>今日訂單</div>
          <div style={{ fontSize: 11, color: C.ink3, marginTop: 2 }}>8/5（三）· 共 18 筆 · 營收 NT$45,200</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 6, padding: '10px 12px', borderBottom: `1px solid ${C.line}` }}>
          {statRow.map((s) => (
            <div key={s.label} style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 17, fontWeight: 800, color: s.color, fontFamily: C.fontMono }}>{s.value}</div>
              <div style={{ fontSize: 9.5, color: C.ink3, marginTop: 1 }}>{s.label}</div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 8, padding: '10px 12px', borderBottom: `1px solid ${C.line}`, overflowX: 'auto' }} className="scroll-hide">
          {alertCards.map((a) => (
            <div key={a.label} style={{
              minWidth: 74, padding: '8px 10px', borderRadius: 10,
              border: a.danger ? `1px solid ${C.red}` : a.active ? `1px solid ${C.navy}` : `1px solid ${C.line}`,
              background: a.danger ? C.redLight : a.active ? C.navyLight : C.white,
            }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, color: a.danger ? C.red : a.active ? C.navy : C.ink3 }}>{a.label}</div>
              <div style={{ fontSize: 17, fontWeight: 800, color: a.danger ? C.red : a.active ? C.navy : C.ink, fontFamily: C.fontMono }}>{a.count}</div>
            </div>
          ))}
        </div>
        <div style={{ padding: '10px 12px', borderBottom: `1px solid ${C.line}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 11px', background: C.bg, border: `1px solid ${C.line}`, borderRadius: 8, fontSize: 12, color: C.ink3 }}>
            <span>🔍</span><span>搜尋訂單編號、乘客、地點...</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6, padding: '10px 12px', borderBottom: `1px solid ${C.line}`, overflowX: 'auto' }} className="scroll-hide">
          {['全部 18', '待接 3', '已派出 4', '進行中 2', '已完成 9'].map((t, i) => (
            <span key={t} style={{
              padding: '5px 11px', borderRadius: 999, fontSize: 11, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
              background: i === 0 ? C.ink : C.white, color: i === 0 ? '#fff' : C.ink2, border: i === 0 ? 'none' : `1px solid ${C.line}`,
            }}>{t}</span>
          ))}
        </div>
        <div className="scroll-hide" style={{ flex: 1, overflowY: 'auto' }}>
          {ORDERS.map((o) => {
            const pt = PILL[o.type];
            const st = STATUS_STYLE[o.status];
            const active = selectedOrder?.id === o.id;
            return (
              <button key={o.id} onClick={() => onSelectOrder(o)} className="press" style={{
                display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer', padding: '12px 14px',
                border: 'none', borderBottom: `1px solid ${C.line}`,
                borderLeft: o.urgent ? `3px solid ${C.red}` : active ? `3px solid ${C.navy}` : '3px solid transparent',
                background: active ? C.navyLight : C.white,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 14, fontWeight: 800 }}>{o.time}</span>
                  <span style={{ fontSize: 10, color: C.ink3, fontFamily: C.fontMono }}>{o.no}</span>
                  <span style={{ marginLeft: 'auto', ...pill(st) }}>{st.label}</span>
                </div>
                <div style={{ fontSize: 12.5, fontWeight: 600, marginTop: 5, color: C.ink }}>{o.from} → {o.to}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
                  <span style={pill(pt)}>{pt.label}</span>
                  <span style={{ fontSize: 10.5, color: C.ink3 }}>{o.pax} 人 · {o.bags} 行李</span>
                  <span style={{ marginLeft: 'auto', fontSize: 12.5, fontWeight: 800, color: C.ink, fontFamily: C.fontMono }}>NT${o.price.toLocaleString()}</span>
                </div>
              </button>
            );
          })}
        </div>
      </div>
      )}

      {/* Right: map + floating detail */}
      <div style={{ flex: 1, minWidth: 0, position: 'relative', background: '#E8EDF3' }}>
        <MapBackground />
        {isNarrow && (
          <div style={{ position: 'absolute', top: 10, left: 10, right: 10, zIndex: 6, display: 'flex', gap: 6, overflowX: 'auto' }} className="scroll-hide">
            {ORDERS.map((o) => (
              <button key={o.id} onClick={() => onSelectOrder(o)} className="press" style={{
                flexShrink: 0, padding: '5px 10px', borderRadius: 999, fontSize: 11, fontWeight: 700, cursor: 'pointer',
                border: selectedOrder?.id === o.id ? `1.5px solid ${C.navy}` : `1px solid ${C.line}`,
                background: selectedOrder?.id === o.id ? '#fff' : 'rgba(255,255,255,.9)', color: selectedOrder?.id === o.id ? C.navy : C.ink2,
              }}>{o.time} {PILL[o.type].label}</button>
            ))}
          </div>
        )}
        <div style={{ position: 'absolute', top: 14, right: 14, width: 320, zIndex: 5, maxHeight: 'calc(100% - 28px)', overflowY: 'auto' }} className="scroll-hide">
          <OrderDetailCard order={selectedOrder} onSwitchView={onSwitchView} />
        </div>
        <div style={{ position: 'absolute', bottom: 14, left: 14, zIndex: 5, background: '#fff', border: `1px solid ${C.line}`, borderRadius: 10, padding: '7px 11px', display: 'flex', gap: 12, fontSize: 10.5, fontWeight: 700, color: C.ink2, boxShadow: '0 2px 8px rgba(15,23,33,.08)' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: C.red }} />司機</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: C.navy }} />上車</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: C.violet }} />下車</span>
        </div>
      </div>
    </div>
  );
}

// 簡化地圖背景（CSS 道路 + 標記點）
function MapBackground() {
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(135deg, #E8EDF3 0%, #DCE4EE 100%)' }} />
      <div style={{ position: 'absolute', left: 0, right: 0, top: '30%', height: 10, background: '#fff', borderTop: '1px solid #C9D3DF', borderBottom: '1px solid #C9D3DF' }} />
      <div style={{ position: 'absolute', left: '22%', top: 0, bottom: 0, width: 8, background: '#fff', borderLeft: '1px solid #C9D3DF', borderRight: '1px solid #C9D3DF' }} />
      <div style={{ position: 'absolute', left: 0, right: 0, top: '68%', height: 6, background: '#fff', borderTop: '1px solid #C9D3DF' }} />
      <div style={{ position: 'absolute', left: '58%', top: 0, bottom: 0, width: 5, background: '#fff', borderLeft: '1px solid #C9D3DF' }} />
      <div style={{ position: 'absolute', left: '20%', top: '28%', width: '42%', height: 3, background: C.navy, transform: 'rotate(-4deg)', opacity: 0.5, borderRadius: 2 }} />
      <MarkerPulse left="20%" top="27%" color={C.red} label="司機" />
      <MarkerPulse left="38%" top="58%" color={C.navy} label="上車" />
      <MarkerPulse left="64%" top="34%" color={C.violet} label="下車" />
    </div>
  );
}

function MarkerPulse({ left, top, color, label }) {
  return (
    <div style={{ position: 'absolute', left, top, zIndex: 3, transform: 'translate(-50%,-50%)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
      <span style={{ width: 15, height: 15, borderRadius: '50%', background: color, border: '3px solid #fff', boxShadow: '0 2px 6px rgba(15,23,33,.25)' }} />
      <span style={{ fontSize: 9.5, fontWeight: 700, background: '#fff', padding: '1px 6px', borderRadius: 4, color, boxShadow: '0 1px 4px rgba(15,23,33,.15)' }}>{label}</span>
    </div>
  );
}

function OrderDetailCard({ order, onSwitchView }) {
  return (
    <div style={cardBase}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <span style={pill(PILL[order.type])}>{PILL[order.type].label}</span>
        <span style={pill(STATUS_STYLE[order.status])}>{STATUS_STYLE[order.status].label}</span>
        <span style={{ marginLeft: 'auto', fontSize: 11, color: C.ink3, fontFamily: C.fontMono }}>{order.no}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span style={{ fontSize: 22, fontWeight: 800, color: C.navy, fontFamily: C.fontMono }}>{order.time}</span>
        <span style={{ fontSize: 12, color: C.ink3 }}>{order.date || '2026-08-11'} · {order.pax} 人 {order.bags} 行李</span>
      </div>
      <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <RouteRow color={C.navy} label="上車" text={order.from} />
        <RouteRow color={C.red} label="下車" text={order.to} />
      </div>
      <div style={{ marginTop: 14, paddingTop: 12, borderTop: `1px dashed ${C.line}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 12, color: C.ink3 }}>訂單金額</span>
        <span style={{ fontSize: 20, fontWeight: 800, color: C.ink, fontFamily: C.fontMono }}>
          NT${(order.price + (order.bonus || 0)).toLocaleString()}
          {order.bonus ? <span style={{ color: C.amber, fontSize: 13 }}>（含加價 ${order.bonus}）</span> : null}
        </span>
      </div>
      {order.driver ? (
        <div style={{ marginTop: 14, padding: 12, background: C.bg, borderRadius: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 34, height: 34, borderRadius: '50%', background: C.navy, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 14 }}>
            {order.driver[0]}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700 }}>{order.driver}</div>
            <div style={{ fontSize: 11, color: C.ink3 }}>{order.car} · 目前位於 {order.district}</div>
          </div>
          <StepBadge step={order.step} />
        </div>
      ) : (
        <div style={{ marginTop: 14 }}>
          <button onClick={() => onSwitchView('ai')} className="press" style={{
            width: '100%', padding: 12, border: 'none', borderRadius: 12, cursor: 'pointer',
            background: C.navy, color: '#fff', fontSize: 14, fontWeight: 700,
          }}>＋ 新增派單</button>
        </div>
      )}
    </div>
  );
}

function RouteRow({ color, label, text }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <span style={{ width: 10, height: 10, borderRadius: '50%', background: color, flexShrink: 0 }} />
      <span style={{ fontSize: 11, color: C.ink3, width: 32, flexShrink: 0 }}>{label}</span>
      <span style={{ fontSize: 13, fontWeight: 600, color: C.ink }}>{text}</span>
    </div>
  );
}

function StepBadge({ step }) {
  const map = {
    STARTED: { bg: C.amberLight, color: C.amber, label: '● 出發' },
    ARRIVED: { bg: C.amberLight, color: C.amber, label: '● 抵達' },
    ONBOARD: { bg: C.greenLight, color: C.green, label: '● 客人上車' },
    DONE: { bg: '#F1EFEB', color: C.ink3, label: '● 完成' },
  };
  const s = map[step] || map.STARTED;
  return <span style={{ ...pill(s), fontSize: 11 }}>{s.label}</span>;
}

// ── AI Parse: AI 一鍵解析 ────────────────────────────
function AiParse({ onSwitchView }) {
  const [raw, setRaw] = React.useState('11/8 早上 7:30 桃機T1 接機 BR266 天母忠義街12巷3號 2大人 2行李 價格1350 陳先生 0912-345-678');
  const [parsed, setParsed] = React.useState(AI_PARSED);
  const [parsing, setParsing] = React.useState(false);

  const runParse = () => {
    setParsing(true);
    setTimeout(() => { setParsed(AI_PARSED); setParsing(false); }, 700);
  };

  const fields = [
    ['類型', parsed.type === 'pickup' ? '接機' : parsed.type === 'dropoff' ? '送機' : '包車'],
    ['航班', parsed.flight],
    ['日期', parsed.date],
    ['時間', parsed.time],
    ['上車', parsed.from],
    ['下車', parsed.to],
    ['人數 / 行李', `${parsed.pax} 人 / ${parsed.bags} 件`],
    ['金額', `NT$${parsed.price}`],
    ['備註', parsed.note],
  ];

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 18 }} className="scroll-hide">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        {/* LEFT: raw paste */}
        <div style={cardBase}>
          <div style={sectionTitle}>貼上 LINE 訊息</div>
          <div style={{ fontSize: 12, color: C.ink3, marginBottom: 10 }}>整段複製貼上，AI 自動拆成結構化訂單。</div>
          <textarea value={raw} onChange={(e) => setRaw(e.target.value)}
            style={{
              width: '100%', height: 180, border: `1px solid ${C.line}`, borderRadius: 12, padding: 12,
              fontSize: 13, lineHeight: 1.7, resize: 'none', outline: 'none', background: C.bg, fontFamily: C.fontMono,
            }} />
          <div style={{ marginTop: 12, display: 'flex', gap: 10 }}>
            <button onClick={runParse} disabled={parsing} className="press" style={{
              padding: '12px 20px', border: 'none', borderRadius: 12, cursor: 'pointer',
              background: C.navy, color: '#fff', fontWeight: 800, fontSize: 14,
            }}>
              {parsing ? '解析中…' : '✦ 一鍵解析'}
            </button>
            <button onClick={() => setRaw('')} className="press" style={{
              padding: '12px 20px', border: `1px solid ${C.line}`, borderRadius: 12, cursor: 'pointer',
              background: C.white, color: C.ink2, fontWeight: 700, fontSize: 14,
            }}>清空</button>
          </div>
        </div>

        {/* RIGHT: parsed fields */}
        <div style={cardBase} className="pop-in" key={parsing ? 'p' : 'd'}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <div style={sectionTitle}>解析結果</div>
            <span style={pill({ bg: C.greenLight, color: C.green })}>✓ 已拆解</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {fields.map(([k, v]) => (
              <div key={k} style={{ padding: '8px 10px', background: C.bg, borderRadius: 10 }}>
                <div style={{ fontSize: 10, color: C.ink3, marginBottom: 2 }}>{k}</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: C.ink }}>{v}</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 14, paddingTop: 12, borderTop: `1px dashed ${C.line}`, display: 'flex', gap: 10 }}>
            <button className="press" style={{ flex: 1, padding: 12, border: 'none', borderRadius: 12, cursor: 'pointer', background: C.navy, color: '#fff', fontWeight: 800, fontSize: 14 }}>
              確認上架
            </button>
            <button onClick={() => onSwitchView('dashboard')} className="press" style={{
              flex: 1, padding: 12, border: `1px solid ${C.line}`, borderRadius: 12, cursor: 'pointer',
              background: C.white, color: C.ink2, fontWeight: 700, fontSize: 14,
            }}>再改一筆</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.ViewsMap = { dashboard: Dashboard, ai: AiParse };
window.AppShell = App;
