// ============ Fleet Intelligence View ============
// Shown when interface === "fleet" and view === "fleet-kb"

function FleetView() {
  const [data, setData] = React.useState({
    insights:  [],
    suppliers: [],
    costs:     [],
    equipment: [],
    context:   {},
  });
  const [loading,    setLoading]    = React.useState(true);
  const [activeTab,  setActiveTab]  = React.useState('insights');
  const [error,      setError]      = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [insRes, supRes, costRes, eqRes] = await Promise.all([
        api.get('/api/fleet/insights?limit=30'),
        api.get('/api/fleet/suppliers'),
        api.get('/api/fleet/costs'),
        api.get('/api/fleet/equipment'),
      ]);
      setData({
        insights:  insRes.insights  || [],
        suppliers: supRes.suppliers || [],
        costs:     costRes.costs    || [],
        equipment: eqRes.equipment  || [],
        context:   {},
      });
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { load(); }, [load]);

  const tabs = [
    { key: 'insights',  label: 'Email Insights',    count: data.insights.length },
    { key: 'equipment', label: 'Equipment',         count: data.equipment.length },
    { key: 'suppliers', label: 'Suppliers',         count: data.suppliers.length },
    { key: 'costs',     label: 'Cost Intelligence', count: data.costs.length },
  ];

  const summaryCards = [
    { label: 'Equipment tracked', value: data.equipment.length, color: 'var(--violet)' },
    { label: 'Suppliers tracked', value: data.suppliers.length, color: 'var(--ok)' },
    { label: 'Cost records',      value: data.costs.length,     color: 'var(--warn)' },
    { label: 'Emails analysed',   value: data.insights.length,  color: 'var(--accent)' },
  ];

  return (
    <div style={{ padding: '24px 28px', maxWidth: 1100, margin: '0 auto' }}>

      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 700, color: 'var(--ink)' }}>
          Fleet Intelligence
        </h2>
        <p style={{ margin: '4px 0 0', fontSize: '0.82rem', color: 'var(--ink-3)' }}>
          Automatically extracted from every fleet-related email
        </p>
      </div>

      {/* Summary cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 24 }}>
        {summaryCards.map(c => (
          <div key={c.label} className="form-card" style={{ padding: '14px 16px', borderRadius: 'var(--radius)', boxShadow: 'var(--shadow-card)' }}>
            <div style={{ fontSize: '1.6rem', fontWeight: 800, color: c.color, fontFamily: 'var(--mono)', lineHeight: 1 }}>
              {loading ? '…' : c.value}
            </div>
            <div style={{ fontSize: '0.75rem', color: 'var(--ink-3)', marginTop: 4 }}>{c.label}</div>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 16, borderBottom: '1px solid var(--line)', paddingBottom: 0 }}>
        {tabs.map(t => (
          <button
            key={t.key}
            onClick={() => setActiveTab(t.key)}
            style={{
              padding: '7px 14px',
              border: 'none',
              borderBottom: activeTab === t.key ? '2px solid var(--ink)' : '2px solid transparent',
              background: 'none',
              cursor: 'pointer',
              fontWeight: activeTab === t.key ? 600 : 400,
              color: activeTab === t.key ? 'var(--ink)' : 'var(--ink-3)',
              fontSize: '0.82rem',
              marginBottom: -1,
              borderRadius: 0,
              whiteSpace: 'nowrap',
            }}
          >
            {t.label}
            {t.count > 0 && (
              <span style={{
                marginLeft: 6, background: 'var(--bg-3)', borderRadius: 10,
                padding: '1px 6px', fontSize: '0.72rem', color: 'var(--ink-3)', fontWeight: 500,
              }}>
                {t.count}
              </span>
            )}
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <button
          className="btn"
          style={{ marginBottom: 4, padding: '5px 12px', fontSize: '0.78rem' }}
          onClick={load}
          disabled={loading}
        >
          {loading ? <I.spin style={{ width: 14, height: 14 }} /> : <I.refresh style={{ width: 14, height: 14 }} />}
          {loading ? ' Loading…' : ' Refresh'}
        </button>
      </div>

      {error && (
        <div className="form-card" style={{ padding: '10px 14px', color: 'var(--urgent)', fontSize: '0.82rem', marginBottom: 16 }}>
          Error: {error}
        </div>
      )}

      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--ink-3)', fontSize: '0.85rem' }}>
          <I.spin style={{ width: 22, height: 22, margin: '0 auto 8px', display: 'block' }} />
          Loading fleet intelligence…
        </div>
      ) : (
        <>
          {activeTab === 'insights'  && <FleetInsightsTab  insights={data.insights} />}
          {activeTab === 'equipment' && <FleetEquipmentTab equipment={data.equipment} />}
          {activeTab === 'suppliers' && <FleetSuppliersTab suppliers={data.suppliers} />}
          {activeTab === 'costs'     && <FleetCostsTab     costs={data.costs} />}
        </>
      )}
    </div>
  );
}

// ---- Insights tab ----
function FleetInsightsTab({ insights }) {
  if (!insights.length) return <FleetEmpty text="No email insights yet. They appear automatically as fleet emails are scanned." />;

  const categoryColor = {
    costing:   'var(--warn)',
    report:    'var(--info)',
    briefing:  'var(--info)',
    meeting:   'var(--ok)',
    sales:     'var(--accent)',
    equipment: 'var(--violet)',
    service:   'var(--violet)',
    supplier:  'var(--ok)',
    other:     'var(--ink-4)',
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {insights.map(ins => {
        let actionItems = [];
        try { actionItems = JSON.parse(ins.action_items || '[]'); } catch {}
        let entities = {};
        try { entities = JSON.parse(ins.entities || '{}'); } catch {}

        return (
          <div key={ins.id} className="form-card" style={{ padding: '12px 16px', borderRadius: 'var(--radius)', boxShadow: 'var(--shadow-card)' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
              <span style={{
                background: categoryColor[ins.category] || 'var(--ink-4)',
                color: '#fff',
                borderRadius: 4,
                padding: '2px 8px',
                fontSize: '0.7rem',
                fontWeight: 700,
                textTransform: 'uppercase',
                letterSpacing: '0.04em',
                flexShrink: 0,
                marginTop: 1,
              }}>
                {ins.category || 'other'}
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: '0.85rem', color: 'var(--ink)', marginBottom: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {ins.subject}
                </div>
                <div style={{ fontSize: '0.8rem', color: 'var(--ink-2)', marginBottom: ins.summary ? 6 : 0 }}>
                  {ins.from_email} · {ins.date ? new Date(ins.date).toLocaleDateString('en-AU', { day: 'numeric', month: 'short', year: 'numeric' }) : ''}
                </div>
                {ins.summary && (
                  <div style={{ fontSize: '0.8rem', color: 'var(--ink-2)', lineHeight: 1.5 }}>
                    {ins.summary}
                  </div>
                )}
                {actionItems.length > 0 && (
                  <div style={{ marginTop: 6, display: 'flex', flexWrap: 'wrap', gap: 5 }}>
                    {actionItems.slice(0, 3).map((a, i) => (
                      <span key={i} style={{
                        background: 'var(--bg-3)', border: '1px solid var(--line)',
                        borderRadius: 4, padding: '1px 7px', fontSize: '0.72rem', color: 'var(--ink-2)',
                      }}>
                        {a}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---- Equipment tab ----
function FleetEquipmentTab({ equipment }) {
  if (!equipment.length) return <FleetEmpty text="No equipment records yet. Fleet numbers and plant names are extracted automatically from emails." />;

  return (
    <div className="form-card" style={{ borderRadius: 'var(--radius)', overflow: 'hidden', boxShadow: 'var(--shadow-card)' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem' }}>
        <thead>
          <tr style={{ background: 'var(--bg-3)', borderBottom: '1px solid var(--line)' }}>
            {['Fleet #', 'Name', 'Category', 'Supplier', 'Last Seen'].map(h => (
              <th key={h} style={{ padding: '9px 14px', textAlign: 'left', fontWeight: 600, color: 'var(--ink-2)', fontSize: '0.75rem', whiteSpace: 'nowrap' }}>
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {equipment.map((eq, i) => (
            <tr key={eq.id} style={{ borderBottom: i < equipment.length - 1 ? '1px solid var(--line)' : 'none', background: i % 2 === 0 ? 'transparent' : 'var(--bg-2)' }}>
              <td style={{ padding: '9px 14px', fontFamily: 'var(--mono)', color: 'var(--violet)', fontWeight: 600 }}>
                {eq.fleet_number || '—'}
              </td>
              <td style={{ padding: '9px 14px', fontWeight: 500 }}>{eq.name || '—'}</td>
              <td style={{ padding: '9px 14px', color: 'var(--ink-2)' }}>{eq.category || '—'}</td>
              <td style={{ padding: '9px 14px', color: 'var(--ink-2)' }}>{eq.supplier || '—'}</td>
              <td style={{ padding: '9px 14px', color: 'var(--ink-3)', fontFamily: 'var(--mono)', fontSize: '0.75rem' }}>
                {eq.last_seen_date || '—'}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ---- Suppliers tab ----
function FleetSuppliersTab({ suppliers }) {
  if (!suppliers.length) return <FleetEmpty text="No supplier records yet. Supplier names and contacts are extracted from emails as they arrive." />;

  const stars = (score) => {
    const n = Math.round(Math.min(10, Math.max(0, score || 5)) / 2);
    return '★'.repeat(n) + '☆'.repeat(5 - n);
  };

  return (
    <div className="form-card" style={{ borderRadius: 'var(--radius)', overflow: 'hidden', boxShadow: 'var(--shadow-card)' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem' }}>
        <thead>
          <tr style={{ background: 'var(--bg-3)', borderBottom: '1px solid var(--line)' }}>
            {['Name', 'Category', 'Email', 'Reliability', 'Last Updated'].map(h => (
              <th key={h} style={{ padding: '9px 14px', textAlign: 'left', fontWeight: 600, color: 'var(--ink-2)', fontSize: '0.75rem', whiteSpace: 'nowrap' }}>
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {suppliers.map((s, i) => (
            <tr key={s.id} style={{ borderBottom: i < suppliers.length - 1 ? '1px solid var(--line)' : 'none', background: i % 2 === 0 ? 'transparent' : 'var(--bg-2)' }}>
              <td style={{ padding: '9px 14px', fontWeight: 600 }}>{s.name || '—'}</td>
              <td style={{ padding: '9px 14px' }}>
                {s.category && (
                  <span style={{ background: 'var(--bg-3)', border: '1px solid var(--line)', borderRadius: 4, padding: '1px 7px', fontSize: '0.72rem', color: 'var(--ink-2)' }}>
                    {s.category}
                  </span>
                )}
              </td>
              <td style={{ padding: '9px 14px', color: 'var(--info)', fontFamily: 'var(--mono)', fontSize: '0.75rem' }}>
                {s.email || '—'}
              </td>
              <td style={{ padding: '9px 14px', color: 'var(--warn)', letterSpacing: '-0.5px', fontSize: '0.82rem' }}>
                {stars(s.reliability_score)}
              </td>
              <td style={{ padding: '9px 14px', color: 'var(--ink-3)', fontFamily: 'var(--mono)', fontSize: '0.75rem' }}>
                {s.updated_at ? s.updated_at.split('T')[0] : '—'}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ---- Costs tab ----
function FleetCostsTab({ costs }) {
  if (!costs.length) return <FleetEmpty text="No cost records yet. Dollar amounts and pricing are extracted automatically from relevant emails." />;

  const totalKnown = costs.reduce((sum, c) => sum + (c.amount || 0), 0);

  const typeColor = {
    service: 'var(--info)',
    part:    'var(--violet)',
    hire:    'var(--accent)',
    fuel:    'var(--warn)',
    repair:  'var(--urgent)',
  };

  return (
    <div>
      {totalKnown > 0 && (
        <div className="form-card" style={{ padding: '12px 16px', marginBottom: 12, borderRadius: 'var(--radius)', boxShadow: 'var(--shadow-card)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div>
            <div style={{ fontSize: '0.72rem', color: 'var(--ink-3)', marginBottom: 2 }}>Total captured (known amounts)</div>
            <div style={{ fontSize: '1.3rem', fontWeight: 800, fontFamily: 'var(--mono)', color: 'var(--ok)' }}>
              ${totalKnown.toLocaleString('en-AU', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
            </div>
          </div>
          <div style={{ flex: 1 }} />
          <div style={{ fontSize: '0.75rem', color: 'var(--ink-3)' }}>
            {costs.length} record{costs.length !== 1 ? 's' : ''}
          </div>
        </div>
      )}

      <div className="form-card" style={{ borderRadius: 'var(--radius)', overflow: 'hidden', boxShadow: 'var(--shadow-card)' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem' }}>
          <thead>
            <tr style={{ background: 'var(--bg-3)', borderBottom: '1px solid var(--line)' }}>
              {['Type', 'Description', 'Amount', 'Supplier', 'Equipment', 'Date', 'Confidence'].map(h => (
                <th key={h} style={{ padding: '9px 14px', textAlign: 'left', fontWeight: 600, color: 'var(--ink-2)', fontSize: '0.75rem', whiteSpace: 'nowrap' }}>
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {costs.map((c, i) => (
              <tr key={c.id} style={{ borderBottom: i < costs.length - 1 ? '1px solid var(--line)' : 'none', background: i % 2 === 0 ? 'transparent' : 'var(--bg-2)' }}>
                <td style={{ padding: '9px 14px' }}>
                  <span style={{ background: typeColor[c.item_type] || 'var(--ink-4)', color: '#fff', borderRadius: 4, padding: '2px 7px', fontSize: '0.7rem', fontWeight: 700 }}>
                    {c.item_type || '—'}
                  </span>
                </td>
                <td style={{ padding: '9px 14px', maxWidth: 200, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {c.description || '—'}
                </td>
                <td style={{ padding: '9px 14px', fontFamily: 'var(--mono)', fontWeight: 700, color: c.amount ? 'var(--ok)' : 'var(--ink-4)' }}>
                  {c.amount != null ? `$${Number(c.amount).toLocaleString('en-AU', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : '—'}
                </td>
                <td style={{ padding: '9px 14px', color: 'var(--ink-2)' }}>{c.supplier || '—'}</td>
                <td style={{ padding: '9px 14px', color: 'var(--violet)', fontFamily: 'var(--mono)', fontSize: '0.75rem' }}>
                  {c.equipment_id || '—'}
                </td>
                <td style={{ padding: '9px 14px', color: 'var(--ink-3)', fontFamily: 'var(--mono)', fontSize: '0.75rem' }}>
                  {c.date || '—'}
                </td>
                <td style={{ padding: '9px 14px' }}>
                  <span style={{
                    fontSize: '0.7rem',
                    color: c.confidence === 'high' ? 'var(--ok)' : c.confidence === 'low' ? 'var(--urgent)' : 'var(--ink-3)',
                    fontWeight: 600,
                  }}>
                    {c.confidence || '—'}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ---- Empty state ----
function FleetEmpty({ text }) {
  return (
    <div className="form-card" style={{
      padding: '40px 24px', textAlign: 'center', borderRadius: 'var(--radius)',
      color: 'var(--ink-3)', fontSize: '0.85rem', lineHeight: 1.6,
    }}>
      <div style={{ fontSize: '2rem', marginBottom: 10 }}>🚛</div>
      {text}
    </div>
  );
}
