// MaxAMove CRM — Financials View (P&L, Expenses, Mileage Log)

const { useState } = React;

function FinancialsView({ jobs }) {
  const [tab, setTab] = useState('pnl');
  const [expenses, setExpenses] = useState(() => {
    try { return JSON.parse(localStorage.getItem('crm_expenses')) || SEED_EXPENSES; } catch { return SEED_EXPENSES; }
  });
  const [mileage, setMileage] = useState(() => {
    try { return JSON.parse(localStorage.getItem('crm_mileage')) || SEED_MILEAGE; } catch { return SEED_MILEAGE; }
  });

  React.useEffect(() => { localStorage.setItem('crm_expenses', JSON.stringify(expenses)); }, [expenses]);
  React.useEffect(() => { localStorage.setItem('crm_mileage', JSON.stringify(mileage)); }, [mileage]);

  const tabs = [
    { id: 'pnl', label: 'P&L Dashboard', icon: 'chart-bar' },
    { id: 'expenses', label: 'Job Expenses', icon: 'dollar-bill' },
    { id: 'mileage', label: 'Mileage Log', icon: 'car' },
  ];

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', marginBottom: 4 }}>Financials</h1>
        <p style={{ color: 'var(--muted)', fontSize: 14 }}>TRUE Profit tracking · Expenses · Mileage · P&L</p>
      </div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 22, borderBottom: '2px solid var(--border)', paddingBottom: 0 }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{
              padding: '9px 18px', border: 'none', background: 'none', cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 13, fontWeight: tab === t.id ? 800 : 500,
              color: tab === t.id ? 'var(--accent)' : 'var(--muted)',
              borderBottom: tab === t.id ? '2px solid var(--accent)' : '2px solid transparent',
              marginBottom: -2, transition: 'all 0.15s', display: 'inline-flex', alignItems: 'center', gap: 6
            }}><Icon name={t.icon} size={14}/>{t.label}</button>
        ))}
      </div>
      {tab === 'pnl' && <PLDashboard expenses={expenses} jobs={jobs} mileage={mileage} />}
      {tab === 'expenses' && <ExpensesTab expenses={expenses} setExpenses={setExpenses} jobs={jobs} />}
      {tab === 'mileage' && <MileageTab mileage={mileage} setMileage={setMileage} />}
    </div>
  );
}

// ─── P&L DASHBOARD ───
function PLDashboard({ expenses, jobs, mileage }) {
  const year = 2026;
  const months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

  // Build monthly data
  const monthlyData = months.map((month, idx) => {
    const mNum = String(idx + 1).padStart(2, '0');
    const prefix = `${year}-${mNum}`;

    // Completed jobs this month
    const monthJobs = jobs.filter(j => j.date && j.date.startsWith(prefix));
    const revenue = monthJobs.filter(j => j.status === 'completed').reduce((s, j) => s + j.value, 0);

    // Expenses this month
    const monthExp = expenses.filter(e => e.date && e.date.startsWith(prefix));
    const crewPay = monthExp.reduce((s, e) => s + (parseFloat(e.crewPay) || 0), 0);
    const fuel = monthExp.reduce((s, e) => s + (parseFloat(e.fuel) || 0), 0);
    const materials = monthExp.reduce((s, e) => s + (parseFloat(e.materials) || 0), 0);
    const other = monthExp.reduce((s, e) => s + (parseFloat(e.other) || 0), 0);
    const totalExp = crewPay + fuel + materials + other;

    // Mileage deduction this month
    const monthMiles = mileage.filter(m => m.date && m.date.startsWith(prefix) && m.reimbursable);
    const mileageDeduction = monthMiles.reduce((s, m) => s + (parseFloat(m.miles) || 0), 0) * IRS_RATE;

    const trueProfit = revenue - totalExp - mileageDeduction;
    const completedJobs = monthJobs.filter(j => j.status === 'completed').length;
    const allJobs = monthJobs.length;

    return { month: month.substring(0, 3), fullMonth: month, revenue, totalExp, crewPay, fuel, materials, other, mileageDeduction, trueProfit, jobs: allJobs, completedJobs };
  });

  const ytd = {
    revenue: monthlyData.reduce((s, m) => s + m.revenue, 0),
    totalExp: monthlyData.reduce((s, m) => s + m.totalExp, 0),
    trueProfit: monthlyData.reduce((s, m) => s + m.trueProfit, 0),
    jobs: monthlyData.reduce((s, m) => s + m.jobs, 0),
    mileageDeduction: monthlyData.reduce((s, m) => s + m.mileageDeduction, 0),
  };

  const margin = ytd.revenue > 0 ? Math.round((ytd.trueProfit / ytd.revenue) * 100) : 0;

  const fmt = (n) => n === 0 ? '—' : (n < 0 ? '-$' + Math.abs(Math.round(n)).toLocaleString() : '$' + Math.round(n).toLocaleString());

  return (
    <div>
      {/* YTD Summary Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
        {[
          { label: 'YTD Revenue', value: '$' + ytd.revenue.toLocaleString(), accent: 'var(--accent)' },
          { label: 'YTD Expenses', value: '$' + Math.round(ytd.totalExp).toLocaleString(), accent: '#ef4444' },
          { label: 'YTD TRUE Profit', value: '$' + Math.round(ytd.trueProfit).toLocaleString(), accent: '#22c55e', big: true },
          { label: 'Profit Margin', value: margin + '%', accent: margin >= 30 ? '#22c55e' : margin >= 15 ? '#f97316' : '#ef4444' },
        ].map(c => (
          <div key={c.label} style={{ background: 'var(--card)', borderRadius: 14, padding: '18px 20px', border: '1px solid var(--border)', borderTop: `3px solid ${c.accent}` }}>
            <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--muted)', marginBottom: 6 }}>{c.label}</div>
            <div style={{ fontSize: c.big ? 26 : 22, fontWeight: 900, fontFamily: 'Poppins', color: c.accent }}>{c.value}</div>
          </div>
        ))}
      </div>

      {/* Monthly P&L Table — mirrors spreadsheet exactly */}
      <div style={{ background: 'var(--card)', borderRadius: 14, border: '1px solid var(--border)', overflow: 'hidden', marginBottom: 20 }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins' }}>Monthly P&L — {year}</div>
          <div style={{ fontSize: 12, color: 'var(--muted)' }}>Mirrors your MaxAMove Dashboard spreadsheet</div>
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ background: 'var(--bg)' }}>
                {['Month', 'Revenue', 'Crew Pay', 'Fuel', 'Materials', 'Other', 'Mileage Deduction', 'Total Expenses', 'TRUE Profit', 'Margin', 'Jobs'].map(h => (
                  <th key={h} style={{ padding: '10px 14px', textAlign: h === 'Month' ? 'left' : 'right', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', whiteSpace: 'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {monthlyData.map((m, i) => {
                const hasData = m.revenue > 0 || m.totalExp > 0 || m.jobs > 0;
                const mrgn = m.revenue > 0 ? Math.round((m.trueProfit / m.revenue) * 100) : null;
                const now = new Date();
                const isCurrent = i === now.getMonth() && year === now.getFullYear();
                return (
                  <tr key={m.month} style={{ borderTop: '1px solid var(--border)', background: isCurrent ? 'var(--accent-light)' : 'transparent', opacity: !hasData && !isCurrent ? 0.45 : 1 }}>
                    <td style={{ padding: '11px 14px', fontWeight: isCurrent ? 800 : 600, color: isCurrent ? 'var(--accent)' : 'var(--text)', whiteSpace: 'nowrap' }}>
                      {isCurrent ? '▶ ' : ''}{m.fullMonth}
                    </td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', fontWeight: 700 }}>{fmt(m.revenue)}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', color: m.crewPay > 0 ? '#ef4444' : 'var(--muted)' }}>{fmt(-m.crewPay)}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', color: m.fuel > 0 ? '#ef4444' : 'var(--muted)' }}>{fmt(-m.fuel)}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', color: m.materials > 0 ? '#ef4444' : 'var(--muted)' }}>{fmt(-m.materials)}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', color: m.other > 0 ? '#ef4444' : 'var(--muted)' }}>{fmt(-m.other)}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', color: m.mileageDeduction > 0 ? '#f97316' : 'var(--muted)' }}>{m.mileageDeduction > 0 ? '-$' + Math.round(m.mileageDeduction).toLocaleString() : '—'}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', fontWeight: 700, color: '#ef4444' }}>{fmt(-m.totalExp - m.mileageDeduction)}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', fontWeight: 900, color: m.trueProfit > 0 ? '#16a34a' : m.trueProfit < 0 ? '#ef4444' : 'var(--muted)' }}>{fmt(m.trueProfit)}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', fontWeight: 700, color: mrgn !== null ? (mrgn >= 30 ? '#16a34a' : mrgn >= 15 ? '#f97316' : '#ef4444') : 'var(--muted)' }}>{mrgn !== null ? mrgn + '%' : '—'}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right' }}>{m.jobs || '—'}</td>
                  </tr>
                );
              })}
            </tbody>
            <tfoot>
              <tr style={{ borderTop: '2px solid var(--border)', background: 'var(--bg)', fontWeight: 900 }}>
                <td style={{ padding: '12px 14px', fontWeight: 900, fontSize: 13 }}>YEAR TOTAL</td>
                <td style={{ padding: '12px 14px', textAlign: 'right', color: 'var(--accent)', fontSize: 13 }}>${ytd.revenue.toLocaleString()}</td>
                <td colSpan={6} style={{ padding: '12px 14px', textAlign: 'right', color: '#ef4444', fontSize: 13 }}>-${Math.round(ytd.totalExp + ytd.mileageDeduction).toLocaleString()}</td>
                <td style={{ padding: '12px 14px', textAlign: 'right', color: ytd.trueProfit >= 0 ? '#16a34a' : '#ef4444', fontSize: 14 }}>${Math.round(ytd.trueProfit).toLocaleString()}</td>
                <td style={{ padding: '12px 14px', textAlign: 'right', color: margin >= 30 ? '#16a34a' : '#f97316', fontSize: 13 }}>{margin}%</td>
                <td style={{ padding: '12px 14px', textAlign: 'right', fontSize: 13 }}>{ytd.jobs}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>

      {/* Expense breakdown donut-style */}
      <div style={{ background: 'var(--card)', borderRadius: 14, padding: 20, border: '1px solid var(--border)' }}>
        <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins', marginBottom: 14 }}>YTD Expense Breakdown</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {[
            { label: 'Crew Pay', value: monthlyData.reduce((s,m) => s+m.crewPay, 0), color: '#ef4444' },
            { label: 'Fuel', value: monthlyData.reduce((s,m) => s+m.fuel, 0), color: '#f97316' },
            { label: 'Materials', value: monthlyData.reduce((s,m) => s+m.materials, 0), color: '#eab308' },
            { label: 'Mileage Deduction', value: monthlyData.reduce((s,m) => s+m.mileageDeduction, 0), color: '#8b5cf6' },
          ].map(e => {
            const pct = ytd.totalExp + ytd.mileageDeduction > 0 ? Math.round((e.value / (ytd.totalExp + ytd.mileageDeduction)) * 100) : 0;
            return (
              <div key={e.label} style={{ background: 'var(--bg)', borderRadius: 10, padding: '14px 16px', borderLeft: `4px solid ${e.color}` }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 6 }}>{e.label}</div>
                <div style={{ fontSize: 20, fontWeight: 900, color: e.color, fontFamily: 'Poppins' }}>${Math.round(e.value).toLocaleString()}</div>
                <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>{pct}% of expenses</div>
                <div style={{ marginTop: 8, height: 4, background: 'var(--border)', borderRadius: 2 }}>
                  <div style={{ width: pct + '%', height: '100%', background: e.color, borderRadius: 2 }} />
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─── EXPENSES TAB ───
function ExpensesTab({ expenses, setExpenses, jobs }) {
  const [showAdd, setShowAdd] = useState(false);
  const blank = { jobId: '', jobName: '', date: new Date().toISOString().split('T')[0], crewPay: '', fuel: '', materials: '', other: '', otherNote: '', revenue: '' };
  const [form, setForm] = useState(blank);

  const totalRevenue = expenses.reduce((s, e) => s + (parseFloat(e.revenue) || 0), 0);
  const totalExp = expenses.reduce((s, e) => s + (parseFloat(e.crewPay)||0) + (parseFloat(e.fuel)||0) + (parseFloat(e.materials)||0) + (parseFloat(e.other)||0), 0);
  const totalProfit = totalRevenue - totalExp;

  const addExpense = () => {
    if (!form.jobName && !form.date) return;
    const id = 'EX' + String(expenses.length + 1).padStart(3, '0');
    setExpenses([{ ...form, id, crewPay: parseFloat(form.crewPay)||0, fuel: parseFloat(form.fuel)||0, materials: parseFloat(form.materials)||0, other: parseFloat(form.other)||0, revenue: parseFloat(form.revenue)||0 }, ...expenses]);
    setShowAdd(false); setForm(blank);
  };

  const del = (id) => { if (confirm('Remove this expense entry?')) setExpenses(expenses.filter(e => e.id !== id)); };

  const FInput = ({ label, k, type='number', placeholder='' }) => (
    <div style={{ marginBottom: 10 }}>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', marginBottom: 4 }}>{label}</label>
      <input type={type} value={form[k]} onChange={e => setForm(p => ({...p, [k]: e.target.value}))} placeholder={placeholder}
        style={{ width: '100%', padding: '8px 12px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none' }} />
    </div>
  );

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 20 }}>
          {[['Revenue Tracked','$'+totalRevenue.toLocaleString(),'var(--accent)'],['Total Expenses','-$'+Math.round(totalExp).toLocaleString(),'#ef4444'],['TRUE Profit','$'+Math.round(totalProfit).toLocaleString(), totalProfit>=0?'#16a34a':'#ef4444']].map(([l,v,c]) => (
            <div key={l} style={{ background: 'var(--card)', borderRadius: 10, padding: '10px 16px', border: '1px solid var(--border)' }}>
              <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', marginBottom: 3 }}>{l}</div>
              <div style={{ fontSize: 18, fontWeight: 900, color: c, fontFamily: 'Poppins' }}>{v}</div>
            </div>
          ))}
        </div>
        <button onClick={() => setShowAdd(true)} style={{ padding: '9px 18px', borderRadius: 10, background: 'var(--accent)', color: '#fff', border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13 }}>+ Add Expenses</button>
      </div>

      <div style={{ background: 'var(--card)', borderRadius: 14, border: '1px solid var(--border)', overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: 'var(--bg)' }}>
              {['Date', 'Job / Customer', 'Revenue', 'Crew Pay', 'Fuel', 'Materials', 'Other', 'Total Exp.', 'TRUE Profit', ''].map(h => (
                <th key={h} style={{ padding: '10px 12px', textAlign: h === 'Date' || h === 'Job / Customer' || h === '' ? 'left' : 'right', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', whiteSpace: 'nowrap' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {expenses.map((e, i) => {
              const exp = (parseFloat(e.crewPay)||0)+(parseFloat(e.fuel)||0)+(parseFloat(e.materials)||0)+(parseFloat(e.other)||0);
              const profit = (parseFloat(e.revenue)||0) - exp;
              return (
                <tr key={e.id} style={{ borderTop: '1px solid var(--border)', background: i%2===0?'transparent':'var(--bg)' }}>
                  <td style={{ padding: '11px 12px', color: 'var(--muted)', fontSize: 12, whiteSpace: 'nowrap' }}>{fmtShortDate(e.date)}</td>
                  <td style={{ padding: '11px 12px', fontWeight: 700 }}>{e.jobName || '—'}</td>
                  <td style={{ padding: '11px 12px', textAlign: 'right', fontWeight: 700, color: 'var(--accent)' }}>${(parseFloat(e.revenue)||0).toLocaleString()}</td>
                  <td style={{ padding: '11px 12px', textAlign: 'right', color: '#ef4444' }}>${(parseFloat(e.crewPay)||0).toLocaleString()}</td>
                  <td style={{ padding: '11px 12px', textAlign: 'right', color: '#f97316' }}>${(parseFloat(e.fuel)||0).toLocaleString()}</td>
                  <td style={{ padding: '11px 12px', textAlign: 'right', color: '#eab308' }}>${(parseFloat(e.materials)||0).toLocaleString()}</td>
                  <td style={{ padding: '11px 12px', textAlign: 'right', color: 'var(--muted)', fontSize: 12 }}>{e.other>0?'$'+e.other:e.otherNote||'—'}</td>
                  <td style={{ padding: '11px 12px', textAlign: 'right', fontWeight: 700, color: '#ef4444' }}>-${Math.round(exp).toLocaleString()}</td>
                  <td style={{ padding: '11px 12px', textAlign: 'right', fontWeight: 900, color: profit>=0?'#16a34a':'#ef4444' }}>${Math.round(profit).toLocaleString()}</td>
                  <td style={{ padding: '11px 12px' }}>
                    <button onClick={() => del(e.id)} style={{ padding: '3px 8px', borderRadius: 6, border: 'none', background: '#fee2e2', color: '#ef4444', cursor: 'pointer', fontSize: 11, fontWeight: 700, display: 'inline-flex', alignItems: 'center' }}><Icon name="x" size={12} color="#ef4444"/></button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {expenses.length === 0 && <div style={{ textAlign: 'center', padding: 40, color: 'var(--muted)' }}>No expense entries yet. Add one above.</div>}
      </div>

      {showAdd && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={() => setShowAdd(false)}>
          <div style={{ background: 'var(--card)', borderRadius: 16, padding: 28, width: 460, maxHeight: '88vh', overflowY: 'auto' }} onClick={e => e.stopPropagation()}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
              <h2 style={{ fontSize: 17, fontWeight: 900, fontFamily: 'Poppins' }}>Add Job Expenses</h2>
              <button onClick={() => setShowAdd(false)} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <FInput label="Date" k="date" type="date" />
              <FInput label="Job Revenue ($)" k="revenue" placeholder="1200" />
              <div style={{ gridColumn: '1/-1' }}><FInput label="Customer / Job Name" k="jobName" type="text" placeholder="Jane Smith" /></div>
              <FInput label="Crew Pay ($)" k="crewPay" placeholder="0" />
              <FInput label="Fuel ($)" k="fuel" placeholder="0" />
              <FInput label="Materials ($)" k="materials" placeholder="0" />
              <FInput label="Other ($)" k="other" placeholder="0" />
              <div style={{ gridColumn: '1/-1' }}><FInput label="Other — Description" k="otherNote" type="text" placeholder="Parking, tolls, etc." /></div>
            </div>
            {form.revenue && (
              <div style={{ margin: '10px 0 14px', padding: 12, background: '#f0fdf4', borderRadius: 10, fontSize: 13, fontWeight: 700, color: '#16a34a', textAlign: 'center' }}>
                TRUE Profit: ${Math.round((parseFloat(form.revenue)||0) - (parseFloat(form.crewPay)||0) - (parseFloat(form.fuel)||0) - (parseFloat(form.materials)||0) - (parseFloat(form.other)||0)).toLocaleString()}
              </div>
            )}
            <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
              <button onClick={() => setShowAdd(false)} style={{ flex: 1, padding: 10, borderRadius: 9, border: '1.5px solid var(--border)', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600 }}>Cancel</button>
              <button onClick={addExpense} style={{ flex: 2, padding: 10, borderRadius: 9, background: 'var(--accent)', border: 'none', color: '#fff', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14 }}>Save Expenses</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── MILEAGE LOG ───
function MileageTab({ mileage, setMileage }) {
  const [showAdd, setShowAdd] = useState(false);
  const blank = { jobName: '', date: new Date().toISOString().split('T')[0], from: '', to: '', miles: '', purpose: '', reimbursable: true };
  const [form, setForm] = useState(blank);

  const totalMiles = mileage.reduce((s, m) => s + (parseFloat(m.miles)||0), 0);
  const deductibleMiles = mileage.filter(m => m.reimbursable).reduce((s, m) => s + (parseFloat(m.miles)||0), 0);
  const irsDeduction = deductibleMiles * IRS_RATE;

  const add = () => {
    if (!form.miles) return;
    const id = 'MI' + String(mileage.length + 1).padStart(3, '0');
    setMileage([{ ...form, id, miles: parseFloat(form.miles)||0 }, ...mileage]);
    setShowAdd(false); setForm(blank);
  };
  const del = (id) => { if (confirm('Remove this mileage entry?')) setMileage(mileage.filter(m => m.id !== id)); };

  const FInput = ({ label, k, type='text', placeholder='' }) => (
    <div style={{ marginBottom: 10 }}>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', marginBottom: 4 }}>{label}</label>
      <input type={type} value={form[k]} onChange={e => setForm(p => ({...p, [k]: e.target.value}))} placeholder={placeholder}
        style={{ width: '100%', padding: '8px 12px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none' }} />
    </div>
  );

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 14 }}>
          {[
            ['Total Miles', totalMiles.toLocaleString() + ' mi', 'var(--accent)'],
            ['IRS Deductible Miles', deductibleMiles.toLocaleString() + ' mi', '#8b5cf6'],
            ['IRS Deduction (' + IRS_RATE + '¢/mi)', '$' + Math.round(irsDeduction).toLocaleString(), '#16a34a'],
          ].map(([l,v,c]) => (
            <div key={l} style={{ background: 'var(--card)', borderRadius: 10, padding: '10px 16px', border: '1px solid var(--border)' }}>
              <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', marginBottom: 3 }}>{l}</div>
              <div style={{ fontSize: 18, fontWeight: 900, color: c, fontFamily: 'Poppins' }}>{v}</div>
            </div>
          ))}
          <div style={{ background: '#fffbeb', borderRadius: 10, padding: '10px 16px', border: '1px solid #fde68a', alignSelf: 'stretch', display: 'flex', alignItems: 'center' }}>
            <div style={{ fontSize: 11, color: '#92400e', fontWeight: 600, maxWidth: 160, lineHeight: 1.4 }}>
              <span style={{display:'inline-flex',alignItems:'center',gap:5}}><Icon name="info" size={13}/> IRS rate 2026: <b>${IRS_RATE}/mile</b></span><br/>Keep this log for your tax filing
            </div>
          </div>
        </div>
        <button onClick={() => setShowAdd(true)} style={{ padding: '9px 18px', borderRadius: 10, background: 'var(--accent)', color: '#fff', border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13 }}>+ Log Miles</button>
      </div>

      <div style={{ background: 'var(--card)', borderRadius: 14, border: '1px solid var(--border)', overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: 'var(--bg)' }}>
              {['Date', 'Job / Purpose', 'From', 'To', 'Miles', 'IRS Value', 'Type', ''].map(h => (
                <th key={h} style={{ padding: '10px 14px', textAlign: 'left', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {mileage.map((m, i) => (
              <tr key={m.id} style={{ borderTop: '1px solid var(--border)', background: i%2===0?'transparent':'var(--bg)' }}>
                <td style={{ padding: '11px 14px', color: 'var(--muted)', fontSize: 12, whiteSpace: 'nowrap' }}>{fmtShortDate(m.date)}</td>
                <td style={{ padding: '11px 14px', fontWeight: 600 }}>{m.jobName || m.purpose || '—'}</td>
                <td style={{ padding: '11px 14px', color: 'var(--muted)', fontSize: 12 }}>{m.from || '—'}</td>
                <td style={{ padding: '11px 14px', color: 'var(--muted)', fontSize: 12 }}>{m.to || '—'}</td>
                <td style={{ padding: '11px 14px', fontWeight: 800 }}>{(parseFloat(m.miles)||0).toLocaleString()}</td>
                <td style={{ padding: '11px 14px', fontWeight: 700, color: m.reimbursable ? '#8b5cf6' : 'var(--muted)' }}>{m.reimbursable ? '$' + Math.round((parseFloat(m.miles)||0) * IRS_RATE).toLocaleString() : '—'}</td>
                <td style={{ padding: '11px 14px' }}>
                  <span style={{ background: m.reimbursable ? '#f3e8ff' : 'var(--bg)', color: m.reimbursable ? '#7c3aed' : 'var(--muted)', padding: '3px 9px', borderRadius: 12, fontSize: 11, fontWeight: 700 }}>
                    {m.reimbursable ? 'Deductible' : 'Non-deductible'}
                  </span>
                </td>
                <td style={{ padding: '11px 14px' }}>
                  <button onClick={() => del(m.id)} style={{ padding: '3px 8px', borderRadius: 6, border: 'none', background: '#fee2e2', color: '#ef4444', cursor: 'pointer', fontSize: 11, fontWeight: 700, display: 'inline-flex', alignItems: 'center' }}><Icon name="x" size={12} color="#ef4444"/></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {mileage.length === 0 && <div style={{ textAlign: 'center', padding: 40, color: 'var(--muted)' }}>No mileage entries. Start logging your drives.</div>}
      </div>

      {showAdd && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={() => setShowAdd(false)}>
          <div style={{ background: 'var(--card)', borderRadius: 16, padding: 28, width: 420 }} onClick={e => e.stopPropagation()}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
              <h2 style={{ fontSize: 17, fontWeight: 900, fontFamily: 'Poppins' }}>Log Mileage</h2>
              <button onClick={() => setShowAdd(false)} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <FInput label="Date" k="date" type="date" />
              <FInput label="Miles Driven" k="miles" type="number" placeholder="0" />
              <div style={{ gridColumn: '1/-1' }}><FInput label="Job / Customer" k="jobName" placeholder="Jane Smith" /></div>
              <FInput label="From" k="from" placeholder="Austin, TX" />
              <FInput label="To" k="to" placeholder="Dallas, TX" />
              <div style={{ gridColumn: '1/-1' }}><FInput label="Purpose" k="purpose" placeholder="Move, supply run, etc." /></div>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
                <input type="checkbox" checked={form.reimbursable} onChange={e => setForm(p => ({...p, reimbursable: e.target.checked}))} style={{ width: 16, height: 16 }} />
                IRS Deductible (business mileage)
              </label>
            </div>
            {form.miles && form.reimbursable && (
              <div style={{ marginBottom: 14, padding: 12, background: '#f3e8ff', borderRadius: 10, fontSize: 13, fontWeight: 700, color: '#7c3aed', textAlign: 'center' }}>
                IRS Deduction: ${Math.round((parseFloat(form.miles)||0) * IRS_RATE).toLocaleString()} ({form.miles} mi × ${IRS_RATE})
              </div>
            )}
            <div style={{ display: 'flex', gap: 10 }}>
              <button onClick={() => setShowAdd(false)} style={{ flex: 1, padding: 10, borderRadius: 9, border: '1.5px solid var(--border)', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600 }}>Cancel</button>
              <button onClick={add} style={{ flex: 2, padding: 10, borderRadius: 9, background: 'var(--accent)', border: 'none', color: '#fff', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14 }}>Save Entry</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { FinancialsView });
