const { useState, useMemo } = React;

function Heatmap({ flips }) {
  const [hover, setHover] = useState(null);
  const year = new Date().getFullYear();
  const today = new Date();
  today.setHours(0,0,0,0);

  const dateCounts = {};
  flips.forEach(f => {
    if (f.status === 'sold' && f.sell_date)
      dateCounts[f.sell_date] = (dateCounts[f.sell_date] || 0) + 1;
  });

  const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const jan1 = new Date(year, 0, 1);
  const dow1 = jan1.getDay();
  const daysBack = dow1 === 0 ? 6 : dow1 - 1;
  const gridStart = new Date(jan1);
  gridStart.setDate(jan1.getDate() - daysBack);

  const weeks = [], monthLabels = [], seenMonths = new Set();
  let d = new Date(gridStart);

  while (true) {
    const week = [];
    for (let i = 0; i < 7; i++) {
      const inYear = d.getFullYear() === year;
      const isFuture = d > today;
      const ds = d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
      const count = dateCounts[ds] || 0;
      let level = -1;
      if (inYear) {
        if (count > 0) level = count >= 3 ? 4 : count === 2 ? 3 : 2;
        else if (isFuture) level = -2;
        else level = 0;
      }
      if (inYear && d.getDate() <= 7 && !seenMonths.has(d.getMonth())) {
        seenMonths.add(d.getMonth());
        monthLabels.push({ weekIdx: weeks.length, label: MONTHS[d.getMonth()] });
      }
      week.push({ ds, level });
      d.setDate(d.getDate() + 1);
    }
    weeks.push(week);
    if (d.getFullYear() > year) break;
  }

  const isDesktop = typeof window !== 'undefined' && window.innerWidth >= 1024;
  const cell = isDesktop ? 15 : 10, gap = isDesktop ? 4 : 3, colW = cell + gap;
  const scrollRef = React.useRef(null);
  React.useEffect(() => {
    if (!scrollRef.current) return;
    const nowWeek = Math.floor((today - gridStart) / (7 * 86400000));
    const scrollTo = Math.max(0, (nowWeek - 6) * colW);
    setTimeout(() => { if (scrollRef.current) scrollRef.current.scrollLeft = scrollTo; }, 50);
  }, []);

  return (
    <div style={{padding: 0, background: 'transparent', borderRadius: 12}}>
      <div style={{display:'flex', gap}}>
        <div style={{display:'flex', flexDirection:'column', gap, width:14, flexShrink:0, paddingTop: isDesktop ? 28 : 20}}>
          {['M','T','W','T','F','S','S'].map((lbl, i) => (
            <div key={i} style={{height:cell, fontSize: isDesktop ? 10 : 8, color:'var(--text-muted)', fontWeight:600, lineHeight:`${cell}px`, textAlign:'right', paddingRight:3}}>{lbl}</div>
          ))}
        </div>
        <div ref={scrollRef} style={{overflowX:'auto', WebkitOverflowScrolling:'touch', scrollbarWidth:'none', msOverflowStyle:'none', flex:1, background: 'transparent', borderRadius: 8, padding: '8px'}}>
          <div style={{display:'inline-flex', flexDirection:'column', gap:0, paddingRight:16, minHeight: '140px'}}>
            <div style={{position:'relative', height:18, marginBottom:2}}>
              {monthLabels.map(({weekIdx, label}) => (
                <span key={label} style={{position:'absolute', left: weekIdx * colW, fontSize:10, color:'var(--text-muted)', fontWeight:700, lineHeight:1, whiteSpace:'nowrap'}}>{label}</span>
              ))}
            </div>
            <div style={{display:'flex', gap, background: 'transparent', padding: '4px', borderRadius: 4, position: 'relative'}}>
              {weeks.map((week, wi) => (
                <div key={wi} style={{display:'flex', flexDirection:'column', gap, flexShrink:0}}>
                  {week.map((c, di) => {
                    const isHovered = hover && hover.ds === c.ds;
                    return (
                      <div key={di}
                        onMouseEnter={() => setHover(c)}
                        onMouseLeave={() => setHover(null)}
                        style={{width:cell, height:cell, borderRadius:2, cursor: 'pointer',
                          background: c.level === -1 ? 'transparent' : c.level === -2 ? 'rgba(0,0,0,0.02)' : c.level === 0 ? 'rgba(0,0,0,0.09)' : c.level === 1 ? 'rgba(45,122,20,0.15)' : c.level === 2 ? 'rgba(45,122,20,0.35)' : c.level === 3 ? 'rgba(45,122,20,0.85)' : 'rgba(45,122,20,1)',
                          border: isHovered ? '1px solid rgba(0,0,0,0.3)' : 'none',
                          boxSizing: 'border-box',
                        }} />
                    );
                  })}
                </div>
              ))}
              {hover && (
                <div style={{
                  position: 'fixed',
                  pointerEvents: 'none',
                  background: 'var(--text)',
                  color: 'white',
                  padding: '8px 12px',
                  borderRadius: 8,
                  fontSize: 12,
                  fontWeight: 500,
                  whiteSpace: 'nowrap',
                  zIndex: 1000,
                  boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                }}>
                  {(() => {
                    const [y, m, d] = hover.ds.split('-');
                    const date = new Date(y, parseInt(m)-1, d);
                    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                    const count = dateCounts[hover.ds] || 0;
                    return `${monthNames[date.getMonth()]} ${date.getDate()}, ${y} · ${count} flip${count !== 1 ? 's' : ''}`;
                  })()}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function GradCard({ gradient, label, value, sub }) {
  return (
    <div style={{background:gradient, borderRadius:18, padding:'16px', flex:1, minWidth:0, position:'relative', overflow:'hidden'}}>
      <div style={{position:'absolute',top:-24,right:-16,width:80,height:80,background:'rgba(255,255,255,0.07)',borderRadius:'50%',pointerEvents:'none'}} />
      <div style={{fontSize:10, color:'rgba(255,255,255,0.6)', textTransform:'uppercase', letterSpacing:'0.5px', fontWeight:600, marginBottom:6}}>{label}</div>
      <div style={{fontSize:26, fontWeight:700, letterSpacing:'-0.5px', color:'white'}}>{value}</div>
      {sub && <div style={{fontSize:11, color:'rgba(255,255,255,0.55)', marginTop:3}}>{sub}</div>}
    </div>
  );
}

function HomeScreen({ navigate }) {
  const { state } = useStore();
  const { flips, overhead } = state;
  const year = new Date().getFullYear();

  const stats = useMemo(() => {
    let gross = 0, completed = 0, openCount = 0, totalP = 0, totalH = 0;
    flips.forEach(f => {
      if (f.status === 'sold' && f.sell_price != null) {
        const p = f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0);
        gross += p; completed++;
        if (f.hours_spent > 0 && p > 0) { totalP += p; totalH += f.hours_spent; }
      } else { openCount++; }
    });
    const tax = Math.round(gross * 0.25 * 100) / 100;
    const net = Math.round((gross - tax) * 100) / 100;
    const hourly = totalH > 0 ? Math.round(totalP / totalH * 100) / 100 : null;
    const totalOverhead = overhead.reduce((s, o) => s + o.amount, 0);
    return { gross: Math.round(gross*100)/100, tax, net, completed, openCount, hourly, totalOverhead };
  }, [flips, overhead]);

  const recent = flips.slice(0, 5);

  return (
    <div className="content">
      <div className="hero-card">
        <div className="hero-glow" />
        <div className="hero-label">Net profit · {year}</div>
        <div className={`hero-amount ${stats.net >= 0 ? 'hero-amount-pos' : 'hero-amount-neg'}`}>
          {stats.net >= 0 ? '↑' : '↓'} {fmt(stats.net)}
        </div>
        <div className="hero-change">{stats.completed} flips completed · {stats.openCount} open</div>
        <div className="hero-pills">
          <div className="hero-pill"><div className="pill-l">Tax est.</div><div className="pill-v pill-warn">{fmt(stats.tax)}</div></div>
          <div className="hero-pill"><div className="pill-l">Gross</div><div className="pill-v pill-ok">{fmt(stats.gross)}</div></div>
          <div className="hero-pill"><div className="pill-l">Flips</div><div className="pill-v">{stats.completed + stats.openCount}</div></div>
        </div>
      </div>

      {/* Overhead shortcut — red gradient card */}
      <div style={{height:4}} />
      <div style={{
        margin:'0 16px',
        background:'linear-gradient(135deg,#b91c1c,#ef4444)',
        borderRadius:18, padding:'14px 16px',
        display:'flex', alignItems:'center', gap:12,
        cursor:'pointer', position:'relative', overflow:'hidden'
      }} onClick={() => navigate('overhead')}>
        <div style={{position:'absolute',top:-20,right:-10,width:80,height:80,background:'rgba(255,255,255,0.07)',borderRadius:'50%',pointerEvents:'none'}} />
        <div style={{width:40,height:40,borderRadius:12,background:'rgba(255,255,255,0.15)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:20,flexShrink:0}}>💸</div>
        <div style={{flex:1, position:'relative'}}>
          <div style={{fontSize:13,fontWeight:700,color:'white'}}>Overhead costs</div>
          <div style={{fontSize:12,color:'rgba(255,255,255,0.65)',marginTop:2}}>
            {stats.totalOverhead > 0 ? `-${fmt(stats.totalOverhead, 2)} logged` : 'Tools, supplies, fees'}
          </div>
        </div>
        <div style={{fontSize:18,color:'rgba(255,255,255,0.6)'}}>›</div>
      </div>

      <div className="section">
        <div className="section-head"><span className="section-title">Flip activity</span><span className="section-sub">{year}</span></div>
      </div>
      <Heatmap flips={flips} />

      <div className="section">
        <div className="section-head"><span className="section-title">Overview</span></div>
      </div>
      <div style={{display:'flex', gap:10, padding:'0 16px'}}>
        <GradCard gradient="linear-gradient(135deg,#1a7a2e,#2ecc5e)" label="Completed" value={stats.completed} sub="flips sold" />
        <GradCard gradient="linear-gradient(135deg,#1a3a8a,#4a7aec)" label="Open" value={stats.openCount} sub="in inventory" />
      </div>
      <div style={{display:'flex', gap:10, padding:'8px 16px 0'}}>
        <GradCard gradient="linear-gradient(135deg,#f59e0b,#f97316)" label="Tax estimate" value={fmt(stats.tax)} sub="set aside ~25%" />
        {stats.hourly ? (
          <GradCard gradient="linear-gradient(135deg,#6d28d9,#a855f7)" label="Hourly rate" value={fmt(stats.hourly)+'/hr'} sub="avg across flips" />
        ) : (
          <div style={{flex:1, background:'#f2f2f7', borderRadius:18, padding:'16px', opacity:0.6}}>
            <div style={{fontSize:10,color:'#888',textTransform:'uppercase',letterSpacing:'0.5px',fontWeight:600,marginBottom:6}}>Hourly rate</div>
            <div style={{fontSize:14,color:'#aaa'}}>Log hours to unlock</div>
          </div>
        )}
      </div>

      <div className="section">
        <div className="section-head">
          <span className="section-title">Recent flips</span>
          <button className="section-sub" style={{background:'none',border:'none',cursor:'pointer'}} onClick={() => navigate('flips')}>See all →</button>
        </div>
      </div>
      {recent.length === 0 ? (
        <div className="empty-state">
          <p>No flips yet.</p>
          <button className="log-btn" onClick={() => navigate('log')}>Log your first flip →</button>
        </div>
      ) : (
        <div className="flips-list">
          {recent.map(f => {
            const profit = flipProfit(f);
            return (
              <div key={f.id} className="flip-item" onClick={() => navigate('flips')} style={{cursor:'pointer'}}>
                <div className="flip-icon" style={{background:catIconBg(f.category),display:'flex',alignItems:'center',justifyContent:'center',fontSize:22,lineHeight:1}}>{itemEmoji(f.item_name)}</div>
                <div className="flip-info">
                  <div className="flip-name">{f.item_name}</div>
                  {f.status === 'sold' ? <div className="flip-meta">{f.platform || '—'} · {f.sell_date}</div> : <div className="flip-meta">Bought {f.buy_date}</div>}
                </div>
                <div className="flip-right">
                  {f.status === 'sold' ? (
                    <><div className={`flip-profit ${profit >= 0 ? 'fp-pos' : 'fp-neg'}`}>{fmtSigned(profit)}</div><div className="flip-date">{fmt(f.buy_price)} → {fmt(f.sell_price)}</div></>
                  ) : <span className="badge-open">open</span>}
                </div>
              </div>
            );
          })}
        </div>
      )}
      <div style={{height:8}} />
    </div>
  );
}

Object.assign(window, { HomeScreen, Heatmap });
