const { useState, useEffect, useRef, useMemo } = React;

const CAT_ICON = {
  'PC Parts':   '🔧',
  'PC Builds':  '🖥️',
  'Laptops':    '💻',
  'Phones':     '📱',
  'Gaming':     '🎮',
  'Sneakers':   '👟',
  'Clothes':    '👕',
  'Watches':    '⌚',
  'Cameras':    '📷',
  'Jewelry':    '💍',
  'Furniture':  '🛋️',
  'Books':      '📚',
  'Toys':       '🧸',
  'Tools':      '🔩',
  'Bikes':      '🚲',
  'Audio':      '🎧',
  'TVs':        '📺',
  'Other':      '📦',
};

function NetProfitChart({ sold }) {
  const canvasRef = useRef(null);
  const chartRef = useRef(null);

  const data = useMemo(() => {
    const sorted = [...sold]
      .filter(f => f.sell_date)
      .sort((a,b) => a.sell_date.localeCompare(b.sell_date));
    let running = 0;
    return sorted.map(f => {
      running += f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0);
      return { date: f.sell_date.slice(5), value: Math.round(running*100)/100, item: f.item_name };
    });
  }, [sold.length]);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || data.length < 2) return;
    if (chartRef.current) chartRef.current.destroy();
    chartRef.current = new Chart(canvas, {
      type: 'line',
      data: {
        labels: data.map(d => d.date),
        datasets: [{
          data: data.map(d => d.value),
          borderColor: '#2563eb',
          backgroundColor: 'rgba(37,99,235,0.12)',
          borderWidth: 2.5,
          pointRadius: 0,
          pointHoverRadius: 4,
          fill: true,
          tension: 0.1,
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false },
          tooltip: {
            callbacks: {
              title: i => data[i[0].dataIndex].item,
              label: i => 'Cumulative: $' + i.parsed.y.toFixed(0)
            }
          }
        },
        scales: {
          x: { grid: { display: false }, ticks: { font: { size: 10 }, maxTicksLimit: 6, color: '#aaa' } },
          y: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { callback: v => '$' + v, font: { size: 10 }, color: '#aaa' } }
        }
      }
    });
    return () => { if (chartRef.current) { chartRef.current.destroy(); chartRef.current = null; } };
  }, [data]);

  if (data.length < 2) return null;

  const finalValue = data[data.length-1].value;
  const color = finalValue >= 0 ? 'var(--green)' : 'var(--red)';

  return (
    <div style={{width: '100%', boxSizing: 'border-box', background:'white', borderRadius:18, padding:'20px', border:'0.5px solid var(--border)'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:8}}>
        <div style={{fontSize:13, fontWeight:600, color:'var(--text)'}}>Net profit over time</div>
        <div style={{fontSize:18, fontWeight:700, color, letterSpacing:'-0.5px'}}>{fmtSigned(finalValue)}</div>
      </div>
      <div style={{position: 'relative', height: 200, width: '100%'}}>
        <canvas ref={canvasRef} />
      </div>
    </div>
  );
}

function MiniLineChart({ data, color = '#2d7a14' }) {
  const canvasRef = useRef(null);
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !data || data.length === 0) return;
    const chart = new Chart(canvas, {
      type: 'line',
      data: {
        labels: data.map(d => d.date ? d.date.slice(5) : ''),
        datasets: [{
          data: data.map(d => d.profit),
          borderColor: color,
          backgroundColor: color + '18',
          borderWidth: 2,
          pointRadius: 4,
          pointBackgroundColor: data.map(d => d.profit >= 0 ? '#2d7a14' : '#cc3333'),
          pointBorderColor: data.map(d => d.profit >= 0 ? '#2d7a14' : '#cc3333'),
          fill: true, tension: 0.3,
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: { display: false },
          tooltip: { callbacks: { title: i => data[i[0].dataIndex].item || '', label: i => '$' + i.parsed.y.toFixed(0) + ' profit' } }
        },
        scales: {
          x: { grid: { display: false }, ticks: { font: { size: 11 } } },
          y: { grid: { color: 'rgba(0,0,0,0.04)' }, ticks: { callback: v => '$' + v, font: { size: 11 } } }
        }
      }
    });
    return () => chart.destroy();
  }, [data]);
  return <canvas ref={canvasRef} height={160} />;
}

function HourlyByCatScreen({ navigate }) {
  const { state } = useStore();
  const sold = state.flips.filter(f => f.status === 'sold' && f.sell_price != null);
  const [expandedCat, setExpandedCat] = useState(null);

  const { categories, catTimelines, totalHourly, noHoursFlips } = useMemo(() => {
    const catMap = {};
    const catTL = {};
    sold.forEach(f => {
      const profit = f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0);
      const cat = f.category || 'Other';
      if (!catMap[cat]) catMap[cat] = { profits: [], hours: [], days: [] };
      catMap[cat].profits.push(profit);
      if (f.hours_spent > 0) catMap[cat].hours.push({ profit, hours: f.hours_spent });
      if (f.buy_date && f.sell_date) catMap[cat].days.push(daysBetween(f.buy_date, f.sell_date));
      if (!catTL[cat]) catTL[cat] = [];
      catTL[cat].push({ date: f.sell_date, profit: Math.round(profit*100)/100, item: f.item_name });
    });
    Object.keys(catTL).forEach(k => catTL[k].sort((a,b) => (a.date||'').localeCompare(b.date||'')));

    const categories = Object.entries(catMap).map(([name, d]) => {
      const totalP = d.hours.reduce((s, h) => s + h.profit, 0);
      const totalH = d.hours.reduce((s, h) => s + h.hours, 0);
      const avg_hourly = totalH > 0 ? totalP / totalH : null;
      return {
        name,
        icon: CAT_ICON[name] || '📦',
        count: d.profits.length,
        avg_profit: d.profits.reduce((a,b) => a+b, 0) / d.profits.length,
        avg_hourly,
        avg_days: d.days.length > 0 ? Math.round(d.days.reduce((a,b)=>a+b,0)/d.days.length) : 0,
        hrs_logged: d.hours.length,
      };
    }).sort((a,b) => (b.avg_hourly || 0) - (a.avg_hourly || 0));

    let totalP = 0, totalH = 0;
    sold.forEach(f => {
      if (f.hours_spent > 0) {
        const p = f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0);
        if (p > 0) { totalP += p; totalH += f.hours_spent; }
      }
    });
    const totalHourly = totalH > 0 ? Math.round(totalP / totalH * 100) / 100 : null;

    // Build noHours with individual flips attached
    const noHoursFlips = sold.filter(f => !f.hours_spent || f.hours_spent === 0);

    return { categories, catTimelines: catTL, totalHourly, noHoursFlips };
  }, [sold.length]);

  const withHours = categories.filter(c => c.avg_hourly != null);
  const noHours = categories.filter(c => c.avg_hourly == null);

  return (
    <div className="content">
      {/* Hero — purple gradient, matches overview cards */}
      {totalHourly ? (
        <div style={{margin:'8px 16px 0', background:'linear-gradient(135deg,#6d28d9,#a855f7)', borderRadius:18, padding:'24px 20px', position:'relative', overflow:'hidden'}}>
          <div style={{position:'absolute',top:-30,right:-20,width:120,height:120,background:'rgba(255,255,255,0.08)',borderRadius:'50%',pointerEvents:'none'}} />
          <div style={{position:'relative'}}>
            <div style={{fontSize:10, color:'rgba(255,255,255,0.65)', textTransform:'uppercase', letterSpacing:'0.6px', marginBottom:6, fontWeight:700}}>Overall hourly rate</div>
            <div style={{fontSize:48, fontWeight:700, letterSpacing:'-2px', color:'white', marginBottom:4}}>
              {fmt(totalHourly)}<span style={{fontSize:22, fontWeight:500, color:'rgba(255,255,255,0.5)'}}>/hr</span>
            </div>
            <div style={{fontSize:13, color:'rgba(255,255,255,0.55)'}}>Across all flips with hours logged</div>
            <div style={{display:'flex', gap:8, marginTop:16}}>
              <div style={{background:'rgba(255,255,255,0.12)', borderRadius:14, padding:'10px 12px', flex:1}}>
                <div style={{fontSize:10, color:'rgba(255,255,255,0.6)', fontWeight:600, marginBottom:4}}>Categories</div>
                <div style={{fontSize:15, fontWeight:700, color:'white'}}>{withHours.length} tracked</div>
              </div>
              <div style={{background:'rgba(255,255,255,0.12)', borderRadius:14, padding:'10px 12px', flex:1}}>
                <div style={{fontSize:10, color:'rgba(255,255,255,0.6)', fontWeight:600, marginBottom:4}}>Best</div>
                <div style={{fontSize:15, fontWeight:700, color:'white'}}>{withHours[0] ? `${withHours[0].icon} ${withHours[0].name}` : '—'}</div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div className="empty-state" style={{marginTop:32}}>
          <p style={{fontSize:28, marginBottom:12}}>⏱</p>
          <p>No hours logged yet. Add hours when logging or selling a flip.</p>
        </div>
      )}

      {withHours.length > 0 && (
        <>
          <div className="section">
            <div className="section-head"><span className="section-title">By category</span><span className="section-sub">Ranked by $/hr</span></div>
          </div>
          <div className="flips-list">
            {withHours.map((cat, i) => {
              const isOpen = expandedCat === i;
              const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : null;
              return (
                <div key={cat.name} className="flip-card">
                  <div className="flip-card-main" onClick={() => setExpandedCat(isOpen ? null : i)}>
                    <div className="flip-icon" style={{background:catIconBg(cat.name), display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, position:'relative'}}>
                      {cat.icon}
                      {medal && <span style={{position:'absolute', top:-4, right:-4, fontSize:10}}>{medal}</span>}
                    </div>
                    <div className="flip-info">
                      <div className="flip-name">{cat.name}</div>
                      <div className="flip-meta">{cat.hrs_logged} flip{cat.hrs_logged !== 1 ? 's' : ''} with hours · avg {cat.avg_days}d to sell</div>
                    </div>
                    <div className="flip-right">
                      <div className="flip-profit fp-pos">{fmt(cat.avg_hourly)}/hr</div>
                      <div className="flip-date">{fmt(cat.avg_profit)} avg profit</div>
                    </div>
                  </div>
                  <div className={`flip-expand ${isOpen ? 'open' : ''}`}>
                    <div className="expand-inner">
                      {isOpen && catTimelines[cat.name] && catTimelines[cat.name].length > 1
                        ? <MiniLineChart data={catTimelines[cat.name]} />
                        : isOpen ? <div style={{fontSize:13,color:'var(--text-muted)',padding:'8px 0'}}>Only 1 sale — chart needs 2+</div>
                        : null}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}

      {noHoursFlips && noHoursFlips.length > 0 && (
        <>
          <div className="section">
            <div className="section-head">
              <span className="section-title">Add hours to flips</span>
              <button className="section-sub" style={{background:'none',border:'none',cursor:'pointer',color:'var(--green)',fontWeight:600}}
                onClick={() => { window._initialTab = 'sold'; navigate('flips'); }}>See all sold →</button>
            </div>
          </div>
          <div style={{margin:'0 16px', background:'white', borderRadius:18, border:'0.5px solid var(--border)', overflow:'hidden'}}>
            {noHoursFlips.map((flip, i) => (
              <HoursRow key={flip.id} flip={flip} last={i === noHoursFlips.length - 1} />
            ))}
            <div style={{padding:'10px 14px', borderTop:'0.5px solid var(--border)', background:'#fafafa'}}>
              <div style={{fontSize:12,color:'var(--text-muted)'}}>Logging hours lets you see your real $/hr per category.</div>
            </div>
          </div>
        </>
      )}
      <div style={{height:8}} />
    </div>
  );
}

function HoursRow({ flip, last }) {
  const { dispatch } = useStore();
  const [hours, setHours] = useState('');
  const [saved, setSaved] = useState(false);

  function save() {
    const h = parseFloat(hours);
    if (!h || h <= 0) return;
    dispatch({ type: 'UPDATE_FLIP', id: flip.id, data: { hours_spent: h } });
    setSaved(true);
  }

  const profit = flipProfit(flip);

  return (
    <div style={{padding:'12px 14px', borderBottom: last ? 'none' : '0.5px solid var(--border)'}}>
      <div style={{display:'flex', alignItems:'center', gap:10, marginBottom: saved ? 0 : 10}}>
        <div className="flip-icon" style={{background:catIconBg(flip.category), display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, lineHeight:1, flexShrink:0}}>
          {itemEmoji(flip.item_name)}
        </div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:13,fontWeight:600,color:'var(--text)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{flip.item_name}</div>
          <div style={{fontSize:11,color:'var(--text-muted)',marginTop:2}}>{flip.sell_date} · {fmt(profit)} profit</div>
        </div>
        {saved && <div style={{fontSize:12,color:'var(--green)',fontWeight:600,flexShrink:0}}>✓ Saved</div>}
      </div>
      {!saved && (
        <div style={{display:'flex', gap:8, alignItems:'center'}}>
          <div style={{display:'flex', alignItems:'center', flex:1, background:'#f2f2f7', borderRadius:10, padding:'0 10px', gap:6}}>
            <span style={{fontSize:14, color:'var(--text-muted)'}}>⏱</span>
            <input
              type="number" placeholder="Hours spent" step="0.5" min="0"
              value={hours} onChange={e => setHours(e.target.value)}
              style={{border:'none',background:'none',fontSize:14,padding:'10px 0',outline:'none',width:'100%',fontFamily:'inherit'}}
            />
          </div>
          <button onClick={save}
            style={{background:'var(--text)',color:'white',border:'none',borderRadius:10,padding:'10px 16px',fontSize:13,fontWeight:600,cursor:'pointer',flexShrink:0,fontFamily:'inherit'}}>
            Save
          </button>
        </div>
      )}
    </div>
  );
}

function InsightsScreen({ navigate }) {
  const { state } = useStore();
  const sold = state.flips.filter(f => f.status === 'sold' && f.sell_price != null);
  const [expandedCat, setExpandedCat] = useState(null);
  const [expandedPlat, setExpandedPlat] = useState(null);

  const enough = sold.length >= 3;

  const { categories, platforms, bestCat, worstCat, totalHourly, catTimelines, platTimelines } = useMemo(() => {
    if (!enough) return {};
    const catMap = {};
    const platMap = {};
    const catTL = {};
    const platTL = {};
    sold.forEach(f => {
      const profit = f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0);
      const cat = f.category || 'Other';
      const plat = f.platform || 'Unknown';
      if (!catMap[cat]) catMap[cat] = { profits:[], hours:[], days:[] };
      catMap[cat].profits.push(profit);
      if (f.hours_spent > 0) catMap[cat].hours.push(profit / f.hours_spent);
      if (f.buy_date && f.sell_date) catMap[cat].days.push(daysBetween(f.buy_date, f.sell_date));
      if (!platMap[plat]) platMap[plat] = [];
      platMap[plat].push(profit);
      if (!catTL[cat]) catTL[cat] = [];
      catTL[cat].push({ date: f.sell_date, profit: Math.round(profit*100)/100, item: f.item_name });
      if (!platTL[plat]) platTL[plat] = [];
      platTL[plat].push({ date: f.sell_date, profit: Math.round(profit*100)/100, item: f.item_name });
    });
    const categories = Object.entries(catMap).map(([name, d]) => ({
      name,
      icon: CAT_ICON[name] || '📦',
      count: d.profits.length,
      avg_profit: d.profits.reduce((a,b)=>a+b,0)/d.profits.length,
      avg_hourly: d.hours.length > 0 ? d.hours.reduce((a,b)=>a+b,0)/d.hours.length : null,
      avg_days: d.days.length > 0 ? Math.round(d.days.reduce((a,b)=>a+b,0)/d.days.length) : 0,
    })).sort((a,b) => (b.avg_hourly||b.avg_profit) - (a.avg_hourly||a.avg_profit));
    const platforms = Object.entries(platMap).map(([name, profits]) => ({
      name, count: profits.length, avg_profit: profits.reduce((a,b)=>a+b,0)/profits.length
    })).sort((a,b) => b.avg_profit - a.avg_profit);
    let totalP = 0, totalH = 0;
    sold.forEach(f => {
      if (f.hours_spent > 0) {
        const p = f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0);
        if (p > 0) { totalP += p; totalH += f.hours_spent; }
      }
    });
    const totalHourly = totalH > 0 ? Math.round(totalP/totalH*100)/100 : null;
    Object.keys(catTL).forEach(k => catTL[k].sort((a,b)=>(a.date||'').localeCompare(b.date||'')));
    Object.keys(platTL).forEach(k => platTL[k].sort((a,b)=>(a.date||'').localeCompare(b.date||'')));
    return { categories, platforms, bestCat: categories[0], worstCat: categories.length > 1 ? categories[categories.length-1] : null, totalHourly, catTimelines: catTL, platTimelines: platTL };
  }, [sold.length]);

  if (!enough) return (
    <div className="content">
      <div className="empty-state" style={{marginTop:32}}>
        <p style={{fontSize:32,marginBottom:12}}>📊</p>
        <p>Log at least 3 sold flips to unlock insights.</p>
      </div>
    </div>
  );

  return (
    <div className="content">

      <div className="section" style={{paddingTop:8}}>
        <div className="section-head"><span className="section-title">Performance summary</span></div>
      </div>
      <div className="cards-row">
        <div className="mini-card" style={{border:'1.5px solid var(--green-light)'}}>
          <div className="mc-label" style={{color:'var(--green)'}}>Best</div>
          <div className="mc-value" style={{fontSize:18,color:'var(--green)',display:'flex',alignItems:'center',gap:6}}>
            <span>{bestCat.icon}</span>{bestCat.name}
          </div>
          <div className="mc-sub">↑ {fmt(bestCat.avg_profit)} avg{bestCat.avg_hourly ? ` · ${fmt(bestCat.avg_hourly)}/hr` : ''}</div>
        </div>
        {worstCat && (() => {
          const isLoss = worstCat.avg_profit < 0;
          return (
            <div className="mini-card" style={{border: isLoss ? '1.5px solid #ffe5e5' : '1.5px solid #e5e5ea'}}>
              <div className="mc-label" style={{color: isLoss ? 'var(--red)' : 'var(--text-muted)'}}>Least efficient</div>
              <div className="mc-value" style={{fontSize:18, color: isLoss ? 'var(--red)' : 'var(--text)', display:'flex', alignItems:'center', gap:6}}>
                <span>{worstCat.icon}</span>{worstCat.name}
              </div>
              <div className="mc-sub">{isLoss ? '↓' : '↑'} {fmt(Math.abs(worstCat.avg_profit))} avg</div>
            </div>
          );
        })()}
      </div>

      <NetProfitChart sold={sold} />

      {/* Hourly rate — clean white card */}
      {totalHourly && (
        <div style={{margin:'8px 16px 0', background:'linear-gradient(135deg,#6d28d9,#a855f7)', borderRadius:18, padding:'16px 20px', cursor:'pointer', display:'flex', alignItems:'center', gap:14, position:'relative', overflow:'hidden'}} onClick={() => navigate('hourly')}>
          <div style={{position:'absolute',top:-20,right:-20,width:80,height:80,background:'rgba(255,255,255,0.08)',borderRadius:'50%',pointerEvents:'none'}} />
          <div style={{position:'relative', flex:1}}>
            <div style={{fontSize:10,color:'rgba(255,255,255,0.65)',fontWeight:600,textTransform:'uppercase',letterSpacing:'0.5px',marginBottom:4}}>Your hourly rate</div>
            <div style={{fontSize:28,fontWeight:700,letterSpacing:'-1px',color:'white'}}>
              {fmt(totalHourly)}<span style={{fontSize:16,fontWeight:500,color:'rgba(255,255,255,0.6)'}}>/hr</span>
            </div>
          </div>
          <div style={{position:'relative', background:'rgba(255,255,255,0.15)', borderRadius:12, padding:'8px 16px', flexShrink:0}}>
            <div style={{fontSize:12,fontWeight:600,color:'white'}}>Details →</div>
          </div>
        </div>
      )}

      <div className="section">
        <div className="section-head"><span className="section-title">By platform</span></div>
      </div>
      <div className="flips-list">
        {platforms.map((p, i) => {
          const isLoss = p.avg_profit < 0;
          const isOpen = expandedPlat === i;
          return (
            <div key={p.name} className="flip-card">
              <div className="flip-card-main" onClick={() => setExpandedPlat(isOpen ? null : i)}>
                <div className="flip-icon ic-blue" style={{display:'flex',alignItems:'center',justifyContent:'center'}}>
                  {p.name==='eBay' ? <img src="ebay-logo.svg" width="32" height="16" style={{objectFit:'contain'}} />
                   : p.name==='Facebook Marketplace' ? <img src="facebook-logo.svg" width="20" height="20" style={{objectFit:'contain'}} />
                   : p.name==='Craigslist' ? <div style={{width:22,height:22,borderRadius:'50%',background:'#532D8E',display:'flex',alignItems:'center',justifyContent:'center',fontSize:9,fontWeight:700,color:'white'}}>CL</div>
                   : p.name==='Local / Cash' ? '📍' : '🏪'}
                </div>
                <div className="flip-info">
                  <div className="flip-name">{p.name}</div>
                  <div className="flip-meta">{p.count} flip{p.count>1?'s':''} sold</div>
                </div>
                <div className="flip-right">
                  <div className={`flip-profit ${isLoss?'fp-neg':'fp-pos'}`}>{fmtSigned(p.avg_profit)}</div>
                  <div className={`flip-chevron ${isOpen?'rotated':''}`}>›</div>
                </div>
              </div>
              <div className={`flip-expand ${isOpen?'open':''}`}>
                <div className="expand-inner">
                  {isOpen && platTimelines[p.name] && platTimelines[p.name].length > 1
                    ? <MiniLineChart data={platTimelines[p.name]} />
                    : isOpen ? <div style={{fontSize:13,color:'var(--text-muted)',padding:'8px 0'}}>Only 1 sale — chart needs 2+</div> : null}
                </div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{height:8}} />
    </div>
  );
}

Object.assign(window, { InsightsScreen, HourlyByCatScreen, NetProfitChart });