const { useMemo: useMemoTax } = React;

const QUARTERS_DEF = [
  { name:'Q1', dates:'Jan – Mar', months:[1,2,3], due:'Apr 15' },
  { name:'Q2', dates:'Apr – Jun', months:[4,5,6], due:'Jun 15' },
  { name:'Q3', dates:'Jul – Sep', months:[7,8,9], due:'Sep 15' },
  { name:'Q4', dates:'Oct – Dec', months:[10,11,12], due:'Jan 15' },
];

function TaxScreen() {
  const { state } = useStore();
  const sold = state.flips.filter(f => f.status === 'sold' && f.sell_price != null);
  const now = new Date();
  const nowYear = now.getFullYear();
  const currentQ = Math.floor((now.getMonth()) / 3);

  const { quarters, grossProfit, taxOwed, totalFlips, scheduleC } = useMemoTax(() => {
    let gross = 0, totalRev = 0, totalCOGS = 0, totalExp = 0, flipsCount = 0;
    const quarters = QUARTERS_DEF.map((qdef, i) => {
      let revenue = 0, cogs = 0, expenses = 0, count = 0;
      sold.forEach(f => {
        if (!f.sell_date) return;
        const m = parseInt(f.sell_date.split('-')[1]);
        const y = parseInt(f.sell_date.split('-')[0]);
        if (y === nowYear && qdef.months.includes(m)) {
          revenue += f.sell_price || 0;
          cogs += f.buy_price || 0;
          expenses += (f.fees||0) + (f.shipping||0);
          count++;
        }
      });
      const profit = revenue - cogs - expenses;
      const tax = profit > 0 ? Math.round(profit * 0.25 * 100) / 100 : 0;
      gross += profit;
      totalRev += revenue;
      totalCOGS += cogs;
      totalExp += expenses;
      flipsCount += count;
      return { ...qdef, revenue, cogs, expenses, profit, tax, active: i === currentQ, count };
    });

    const taxOwed = gross > 0 ? Math.round(gross * 0.25 * 100) / 100 : 0;
    return {
      quarters,
      grossProfit: Math.round(gross * 100) / 100,
      taxOwed,
      totalFlips: flipsCount,
      scheduleC: {
        revenue: Math.round(totalRev*100)/100,
        cogs: Math.round(totalCOGS*100)/100,
        expenses: Math.round(totalExp*100)/100,
        net_profit: Math.round(gross*100)/100,
        net_after_tax: Math.round((gross - taxOwed)*100)/100
      }
    };
  }, [sold.length, state.flips]);

  function exportCSV() {
    const rows = [
      ['Schedule C Export — Fliptaxy','','','','',''],
      [],
      ['Date Sold','Item','Category','Revenue','COGS','Expenses','Net Profit','Hours'],
    ];
    sold.forEach(f => {
      const profit = f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0);
      rows.push([f.sell_date, f.item_name, f.category||'', f.sell_price, f.buy_price, (f.fees||0)+(f.shipping||0), Math.round(profit*100)/100, f.hours_spent||0]);
    });
    const csv = rows.map(r => r.join(',')).join('\n');
    const a = document.createElement('a');
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'fliptaxy_schedule_c.csv';
    a.click();
  }

  return (
    <div className="content">
      {/* Hero */}
      <div className="tax-hero-card">
        <div className="tax-hero-label">Estimated tax owed · {nowYear}</div>
        <div className="tax-hero-amount">{fmt(taxOwed, 2)}</div>
        <div className="tax-hero-sub">Based on {fmt(grossProfit, 2)} gross profit at 25%</div>
        <div className="hero-pills" style={{marginTop:16}}>
          <div className="hero-pill" style={{background:'rgba(0,0,0,0.06)'}}>
            <div className="pill-l" style={{color:'rgba(0,0,0,0.45)'}}>Gross profit</div>
            <div className="pill-v" style={{color:'#1a1a1a'}}>{fmt(grossProfit, 2)}</div>
          </div>
          <div className="hero-pill" style={{background:'rgba(0,0,0,0.06)'}}>
            <div className="pill-l" style={{color:'rgba(0,0,0,0.45)'}}>After tax</div>
            <div className="pill-v" style={{color:'var(--green)'}}>{fmt(grossProfit - taxOwed, 2)}</div>
          </div>
          <div className="hero-pill" style={{background:'rgba(0,0,0,0.06)'}}>
            <div className="pill-l" style={{color:'rgba(0,0,0,0.45)'}}>Flips</div>
            <div className="pill-v" style={{color:'#1a1a1a'}}>{totalFlips}</div>
          </div>
        </div>
      </div>

      {/* Quarters */}
      <div className="section">
        <div className="section-head">
          <span className="section-title">Quarterly breakdown</span>
          <span className="section-sub">{nowYear}</span>
        </div>
      </div>

      <div className="tax-quarters">
        {quarters.map(q => (
          <div key={q.name} className={`tax-quarter-card ${q.active ? 'tq-active' : ''}`}>
            <div className="tq-top">
              <div>
                <div className="tq-label">{q.name}</div>
                <div className="tq-dates">{q.dates}</div>
              </div>
              {q.active ? (
                <div className="tq-badge">Current</div>
              ) : q.count === 0 ? (
                <div className="tq-badge tq-badge-warn" style={{fontSize:10}}>No flips</div>
              ) : null}
            </div>
            <div className="tq-row"><span className="tq-key">Revenue</span><span className="tq-val">{fmt(q.revenue, 2)}</span></div>
            <div className="tq-row"><span className="tq-key">Cost of goods</span><span className="tq-val">-{fmt(q.cogs, 2)}</span></div>
            <div className="tq-row"><span className="tq-key">Expenses</span><span className="tq-val">-{fmt(q.expenses, 2)}</span></div>
            <div className="tq-divider" />
            <div className="tq-row">
              <span className="tq-key" style={{fontWeight:600}}>Gross profit</span>
              <span className={`tq-val ${q.profit >= 0 ? 'fp-pos' : 'fp-neg'}`} style={{fontWeight:600}}>{fmt(q.profit, 2)}</span>
            </div>
            <div className="tq-row"><span className="tq-key">Est. tax (25%)</span><span className="tq-val tq-tax">{fmt(q.tax, 2)}</span></div>
            <div className="tq-row">
              <span className="tq-key" style={{fontWeight:600}}>Net profit (after tax)</span>
              <span className="tq-val fp-pos" style={{fontWeight:600}}>{fmt(q.profit - q.tax, 2)}</span>
            </div>
          </div>
        ))}
      </div>

      {/* Schedule C */}
      <div className="section">
        <div className="section-head">
          <span className="section-title">Schedule C summary</span>
          <span className="section-sub">US · {nowYear}</span>
        </div>
      </div>
      <div className="tax-schedule">
        <div className="tq-row"><span className="tq-key">Gross receipts (Line 1)</span><span className="tq-val">{fmt(scheduleC.revenue, 2)}</span></div>
        <div className="tq-row"><span className="tq-key">Cost of goods (Line 4)</span><span className="tq-val">-{fmt(scheduleC.cogs, 2)}</span></div>
        <div className="tq-row"><span className="tq-key">Other expenses (Line 27)</span><span className="tq-val">-{fmt(scheduleC.expenses, 2)}</span></div>
        <div className="tq-divider" />
        <div className="tq-row">
          <span className="tq-key" style={{fontWeight:600}}>Gross profit (Line 31)</span>
          <span className="tq-val fp-pos" style={{fontWeight:600}}>{fmt(scheduleC.net_profit, 2)}</span>
        </div>
        <div className="tq-row"><span className="tq-key">Est. tax (25%)</span><span className="tq-val tq-tax">-{fmt(taxOwed, 2)}</span></div>
        <div className="tq-divider" />
        <div className="tq-row">
          <span className="tq-key" style={{fontWeight:600, color:'var(--green)'}}>Net profit (after tax)</span>
          <span className="tq-val fp-pos" style={{fontWeight:700}}>{fmt(scheduleC.net_after_tax, 2)}</span>
        </div>
      </div>

      <div style={{padding:'0 16px 8px', display:'flex', justifyContent:'center'}}>
        <button className="log-btn" style={{display:'inline-block', width:'auto', padding:'14px 28px'}} onClick={exportCSV}>
          Export CSV for Schedule C
        </button>
      </div>

      <div className="tax-disclaimer">
        Estimate for planning purposes only. Consult a tax professional for your actual filing.
      </div>
    </div>
  );
}

Object.assign(window, { TaxScreen });
