const { useState, useMemo, useEffect } = React;

function DesktopDashboard({ navigate, openPanel }) {
  const { state, isAnonymous } = useStore();
  const { flips, overhead } = state;
  const [filter, setFilter] = useState('all');
  
  const year = new Date().getFullYear();
  
  const stats = useMemo(() => {
    let gross = 0, completed = 0, openCount = 0;
    let 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;
    return { gross: Math.round(gross*100)/100, tax, net, completed, openCount, hourly };
  }, [flips]);
  
  const filteredFlips = useMemo(() => {
    if (filter === 'all') return flips;
    if (filter === 'open') return flips.filter(f => f.status === 'open');
    if (filter === 'sold') return flips.filter(f => f.status === 'sold');
    return flips.filter(f => f.category === filter);
  }, [flips, filter]);
  
  const recent = filteredFlips.slice(0, 10);
  
  const sold = flips.filter(f => f.status === 'sold' && f.sell_price != null);
  const enough = sold.length >= 3;
  
  const { categories, platforms } = useMemo(() => {
    if (!enough) return { categories: [], platforms: [] };
    const catMap = {};
    const platMap = {};
    
    sold.forEach(f => {
      const profit = flipProfit(f);
      if (!catMap[f.category]) catMap[f.category] = [];
      catMap[f.category].push(profit);
      
      const plat = f.platform || 'Other';
      if (!platMap[plat]) platMap[plat] = [];
      platMap[plat].push(profit);
    });
    
    const categories = Object.entries(catMap).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);
    
    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);
    
    return { categories, platforms };
  }, [sold.length]);
  
  return (
    <div className="dashboard">
      <div className="sidebar-left">
        <DashboardHero stats={stats} year={year} />
        {isAnonymous && (
          <div style={{
            background:'#fff8e8', border:'1px solid #f59e0b',
            borderRadius:12, padding:'10px 14px', marginTop:8,
            fontSize:13, color:'#a05c00', display:'flex',
            alignItems:'center', gap:8,
          }}>
            <span>⚡</span>
            <span>Anonymous demo — {flips.length}/5 flips. Sign up to save unlimited data.</span>
          </div>
        )}
        <DashboardOverview stats={stats} setFilter={setFilter} filter={filter} />
        <TaxSummary />
      </div>
      
      <div className="main-content">
        <div className="dashboard-card">
          <div className="section-head">
            <span className="section-title">Flip Activity</span>
            <span className="section-sub">{year}</span>
          </div>
          <div className="desktop-heatmap">
            <Heatmap flips={flips} />
          </div>
        </div>
        
        <div className="insights-charts">
          {enough && (
            <div style={{position: 'relative', width: '100%', boxSizing: 'border-box'}}>
              <NetProfitChart sold={sold} />
              <button
                onClick={() => openPanel('insights')}
                style={{
                  width: '100%',
                  padding: '13px 20px',
                  background: '#1a1a1a',
                  color: 'white',
                  border: 'none',
                  borderRadius: 14,
                  fontSize: 14,
                  fontWeight: 600,
                  cursor: 'pointer',
                  marginTop: 12,
                  fontFamily: 'inherit',
                  display: 'block',
                  textAlign: 'center',
                }}
              >
                Show Details →
              </button>
            </div>
          )}
          {enough && categories.length > 0 && <CategoryPerformance categories={categories.slice(0, 5)} />}
          {enough && platforms.length > 0 && <PlatformPerformance platforms={platforms.slice(0, 3)} />}
        </div>
      </div>
      
      <div className="sidebar-right">
        <RecentFlips flips={recent} navigate={navigate} />
        <QuickActions navigate={navigate} />
        <MiniStats stats={stats} categories={categories} />
      </div>
    </div>
  );
}

function DashboardHero({ stats, year }) {
  const profitMargin = stats.gross > 0 ? Math.round((stats.net / stats.gross) * 100) : 0;
  const avgProfitPerFlip = stats.completed > 0 ? Math.round(stats.net / stats.completed) : 0;
  
  return (
    <div className="dashboard-card dashboard-hero">
      <div style={{position: 'relative', zIndex: 1}}>
        <div style={{fontSize: 12, color: 'rgba(255,255,255,0.7)', textTransform: 'uppercase', letterSpacing: '0.5px', fontWeight: 600, marginBottom: 8}}>
          Net Profit · {year}
        </div>
        <div style={{fontSize: 42, fontWeight: 700, letterSpacing: '-1px', marginBottom: 8}}>
          {stats.net >= 0 ? '↑' : '↓'} {fmt(stats.net)}
        </div>
        <div style={{fontSize: 14, color: 'rgba(255,255,255,0.6)', marginBottom: 20}}>
          {stats.completed} flips completed · {stats.openCount} open
        </div>
        
        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16}}>
          <div style={{background: 'rgba(255,255,255,0.15)', borderRadius: 12, padding: '12px'}}>
            <div style={{fontSize: 10, color: 'rgba(255,255,255,0.8)', fontWeight: 600, marginBottom: 2}}>Tax Est.</div>
            <div style={{fontSize: 16, fontWeight: 700}}>{fmt(stats.tax)}</div>
          </div>
          <div style={{background: 'rgba(255,255,255,0.15)', borderRadius: 12, padding: '12px'}}>
            <div style={{fontSize: 10, color: 'rgba(255,255,255,0.8)', fontWeight: 600, marginBottom: 2}}>Gross</div>
            <div style={{fontSize: 16, fontWeight: 700}}>{fmt(stats.gross)}</div>
          </div>
        </div>
        
        <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12}}>
          <div style={{background: 'rgba(255,255,255,0.1)', borderRadius: 8, padding: '10px'}}>
            <div style={{fontSize: 9, color: 'rgba(255,255,255,0.7)', fontWeight: 600, marginBottom: 1}}>Margin</div>
            <div style={{fontSize: 14, fontWeight: 600}}>{profitMargin}%</div>
          </div>
          <div style={{background: 'rgba(255,255,255,0.1)', borderRadius: 8, padding: '10px'}}>
            <div style={{fontSize: 9, color: 'rgba(255,255,255,0.7)', fontWeight: 600, marginBottom: 1}}>Avg/Flip</div>
            <div style={{fontSize: 14, fontWeight: 600}}>{fmt(avgProfitPerFlip)}</div>
          </div>
        </div>
        
        {stats.hourly && (
          <div style={{marginTop: 12, padding: '10px', background: 'rgba(255,255,255,0.1)', borderRadius: 8}}>
            <div style={{fontSize: 9, color: 'rgba(255,255,255,0.7)', fontWeight: 600, marginBottom: 1}}>Hourly Rate</div>
            <div style={{fontSize: 14, fontWeight: 600}}>{fmt(stats.hourly)}/hr</div>
          </div>
        )}
      </div>
    </div>
  );
}

function DashboardOverview({ stats, setFilter, filter }) {
  const successRate = stats.completed > 0 ? Math.round((stats.completed / (stats.completed + stats.openCount)) * 100) : 0;

  const card = (gradient, clickable, active, onClick, labelText, valueText, subText) => (
    <div onClick={onClick} style={{
      background: gradient,
      borderRadius: 14,
      padding: '12px 14px',
      cursor: clickable ? 'pointer' : 'default',
      border: active ? '2px solid rgba(255,255,255,0.55)' : '2px solid transparent',
      boxSizing: 'border-box',
      height: 100,
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'space-between',
      overflow: 'hidden',
    }}>
      <div style={{fontSize:10, color:'rgba(255,255,255,0.7)', textTransform:'uppercase', letterSpacing:'0.6px', fontWeight:600}}>{labelText}</div>
      <div style={{fontSize:26, fontWeight:700, letterSpacing:'-0.5px', color:'white', lineHeight:1}}>{valueText}</div>
      <div style={{fontSize:11, color:'rgba(255,255,255,0.6)'}}>{subText}</div>
    </div>
  );

  return (
    <div className="dashboard-card">
      <div style={{fontSize:14, fontWeight:600, marginBottom:12, color:'var(--text)', display:'flex', alignItems:'center', gap:6}}>
        <span>📊</span> Overview
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8}}>
        {card('linear-gradient(135deg,#1a7a2e,#2ecc5e)', true, filter==='sold', () => setFilter(filter==='sold'?'all':'sold'), 'Completed', stats.completed, successRate + '% success')}
        {card('linear-gradient(135deg,#1a3a8a,#4a7aec)', true, filter==='open', () => setFilter(filter==='open'?'all':'open'), 'Open Flips', stats.openCount, stats.openCount > 0 ? 'in inventory' : 'all sold')}
        {card('linear-gradient(135deg,#f59e0b,#f97316)', false, false, null, 'Tax Estimate', fmt(stats.tax), 'set aside ~25%')}
        {card('linear-gradient(135deg,#6d28d9,#a855f7)', false, false, null, 'Hourly Rate', stats.hourly ? fmt(stats.hourly)+'/hr' : '—', stats.hourly ? 'avg per hour' : 'log hours to unlock')}
      </div>
      {filter !== 'all' && (
        <div style={{marginTop:10, padding:'8px 12px', background:'var(--bg)', borderRadius:8, display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <div style={{fontSize:12, color:'var(--text)'}}>Filter: <strong>{filter==='sold'?'Completed':'Open'}</strong></div>
          <button onClick={() => setFilter('all')} style={{fontSize:12, color:'var(--green)', background:'none', border:'none', cursor:'pointer', fontWeight:600}}>Clear ✕</button>
        </div>
      )}
    </div>
  );
}

function TaxSummary() {
  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 = [
    { name: 'Q1', months: [1,2,3], profit: 0, tax: 0 },
    { name: 'Q2', months: [4,5,6], profit: 0, tax: 0 },
    { name: 'Q3', months: [7,8,9], profit: 0, tax: 0 },
    { name: 'Q4', months: [10,11,12], profit: 0, tax: 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) {
      const q = Math.floor((m - 1) / 3);
      if (q >= 0 && q < 4) {
        const profit = f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0);
        quarters[q].profit += profit;
        quarters[q].tax += profit > 0 ? profit * 0.25 : 0;
      }
    }
  });
  
  return (
    <div className="dashboard-card">
      <div style={{fontSize: 16, fontWeight: 600, marginBottom: 16, color: 'var(--text)'}}>Tax Summary</div>
      <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
        {quarters.map((q, i) => (
          <div 
            key={q.name} 
            style={{ 
              display: 'flex', 
              justifyContent: 'space-between', 
              padding: '8px 12px', 
              borderRadius: 8,
              background: i === currentQ ? 'rgba(37, 99, 235, 0.1)' : 'transparent',
              border: i === currentQ ? '1px solid rgba(37, 99, 235, 0.3)' : '1px solid var(--border)'
            }}
          >
            <span style={{fontSize: 14, fontWeight: 500, color: 'var(--text)'}}>{q.name}</span>
            <span style={{fontSize: 14, fontWeight: 600, color: q.profit >= 0 ? 'var(--green)' : 'var(--red)'}}>
              {fmt(Math.round(q.profit * 100) / 100)}
            </span>
          </div>
        ))}
      </div>
      <div style={{marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--border)'}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
          <span style={{fontSize: 12, color: 'var(--text-muted)'}}>Total Tax Owed</span>
          <span style={{fontSize: 16, fontWeight: 700, color: 'var(--red)'}}>
            {fmt(Math.round(quarters.reduce((sum, q) => sum + q.tax, 0) * 100) / 100)}
          </span>
        </div>
      </div>
    </div>
  );
}

function RecentFlips({ flips, navigate }) {
  return (
    <div className="dashboard-card">
      <div style={{fontSize: 16, fontWeight: 600, marginBottom: 20, color: 'var(--text)', display: 'flex', alignItems: 'center', gap: 8}}>
        <span>🔄</span> Recent Flips
      </div>
      <div className="recent-flips-desktop">
        {flips.length === 0 ? (
          <div style={{textAlign: 'center', padding: '32px 0', color: 'var(--text-muted)'}}>
            <div style={{fontSize: 32, marginBottom: 8}}>📦</div>
            <div style={{fontSize: 14}}>No flips yet</div>
            <div style={{fontSize: 12, marginTop: 4}}>Start logging your first flip!</div>
          </div>
        ) : (
          <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
            {flips.map(f => {
              const profit = flipProfit(f);
              const daysAgo = f.status === 'sold' ? 
                daysBetween(f.sell_date) : 
                daysBetween(f.buy_date);
              const isRecent = daysAgo <= 7;
              
              return (
                <div 
                  key={f.id} 
                  className="flip-item" 
                  onClick={() => navigate('flips')} 
                  style={{
                    cursor: 'pointer',
                    padding: '12px',
                    borderRadius: 8,
                    background: isRecent ? 'var(--surface)' : 'transparent',
                    border: isRecent ? '1px solid var(--border)' : '1px solid transparent',
                    transition: 'all 0.2s'
                  }}
                >
                  <div style={{display: 'flex', alignItems: 'center', gap: 12}}>
                    <div 
                      className="flip-icon" 
                      style={{
                        background: catIconBg(f.category),
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontSize: 20,
                        lineHeight: 1,
                        width: 40,
                        height: 40,
                        borderRadius: 8,
                        flexShrink: 0
                      }}
                    >
                      {itemEmoji(f.item_name)}
                    </div>
                    <div className="flip-info" style={{flex: 1, minWidth: 0}}>
                      <div className="flip-name" style={{fontSize: 14, fontWeight: 500, marginBottom: 2}}>
                        {f.item_name}
                      </div>
                      <div className="flip-meta" style={{fontSize: 11, color: 'var(--text-muted)'}}>
                        {f.status === 'sold' ? 
                          `${f.platform || '—'} · ${f.sell_date}` : 
                          `Bought ${f.buy_date}`
                        }
                        {isRecent && <span style={{color: 'var(--green)', marginLeft: 4}}>• Recent</span>}
                      </div>
                    </div>
                    <div className="flip-right" style={{textAlign: 'right', flexShrink: 0}}>
                      {f.status === 'sold' ? (
                        <div>
                          <div className={`flip-profit ${profit >= 0 ? 'fp-pos' : 'fp-neg'}`} style={{fontSize: 14, fontWeight: 600}}>
                            {fmtSigned(profit)}
                          </div>
                          <div style={{fontSize: 10, color: 'var(--text-muted)'}}>
                            {daysAgo}d ago
                          </div>
                        </div>
                      ) : (
                        <div>
                          <span className="badge-open" style={{fontSize: 10, padding: '4px 8px', borderRadius: 12, background: 'var(--surface)', color: 'var(--text)'}}>
                            open
                          </span>
                          <div style={{fontSize: 10, color: 'var(--text-muted)', marginTop: 2}}>
                            {daysAgo}d ago
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
        
        {flips.length > 0 && (
          <button 
            onClick={() => navigate('flips')}
            style={{
              width: '100%',
              padding: '10px',
              marginTop: 12,
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 8,
              cursor: 'pointer',
              fontSize: 13,
              color: 'var(--text)',
              fontWeight: 500,
              transition: 'all 0.2s'
            }}
          >
            View All Flips →
          </button>
        )}
      </div>
    </div>
  );
}

function QuickActions({ navigate }) {
  return (
    <div className="dashboard-card">
      <div style={{fontSize: 16, fontWeight: 600, marginBottom: 16, color: 'var(--text)'}}>
        Quick Actions
      </div>
      <div className="quick-actions">
        <button className="quick-action-btn" onClick={() => navigate('log')}>
          + Log New Flip
        </button>
        <button className="quick-action-btn" onClick={() => navigate('overhead')}>
          + Add Overhead
        </button>
        <button className="quick-action-btn" onClick={() => navigate('flips')}>
          View All Flips
        </button>
      </div>
    </div>
  );
}

function MiniStats({ stats, categories }) {
  const bestCategory = categories && categories.length > 0 ? categories[0] : null;
  
  return (
    <div className="dashboard-card">
      <div style={{fontSize: 16, fontWeight: 600, marginBottom: 16, color: 'var(--text)'}}>
        Quick Stats
      </div>
      <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
        <div>
          <div style={{fontSize: 12, color: 'var(--text-muted)', marginBottom: 2}}>Avg Profit/Flip</div>
          <div style={{fontSize: 16, fontWeight: 600, color: 'var(--text)'}}>
            {stats.completed > 0 ? fmt(stats.net / stats.completed) : '—'}
          </div>
        </div>
        
        {bestCategory && (
          <div>
            <div style={{fontSize: 12, color: 'var(--text-muted)', marginBottom: 2}}>Best Category</div>
            <div style={{fontSize: 14, fontWeight: 600, color: 'var(--text)'}}>
              {bestCategory.name}
            </div>
            <div style={{fontSize: 12, color: 'var(--green)'}}>
              {fmt(bestCategory.avg_profit)} avg
            </div>
          </div>
        )}
        
        <div>
          <div style={{fontSize: 12, color: 'var(--text-muted)', marginBottom: 2}}>Success Rate</div>
          <div style={{fontSize: 16, fontWeight: 600, color: 'var(--text)'}}>
            {stats.completed > 0 ? Math.round((stats.completed / (stats.completed + stats.openCount)) * 100) : 0}%
          </div>
        </div>
      </div>
    </div>
  );
}

function CategoryPerformance({ categories }) {
  return (
    <div className="chart-container">
      <div style={{fontSize: 16, fontWeight: 600, marginBottom: 16, color: 'var(--text)'}}>
        Top Categories
      </div>
      <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
        {categories.map((cat, i) => (
          <div key={cat.name} style={{display: 'flex', alignItems: 'center', gap: 12}}>
            <div style={{width: 30, height: 30, borderRadius: 8, background: catIconBg(cat.name), display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16}}>
              {cat.name === 'PC Parts' ? '🔧' : cat.name === 'Laptops' ? '💻' : cat.name === 'Phones' ? '📱' : cat.name === 'Gaming' ? '🎮' : '📦'}
            </div>
            <div style={{flex: 1}}>
              <div style={{fontSize: 14, fontWeight: 500, color: 'var(--text)'}}>{cat.name}</div>
              <div style={{fontSize: 12, color: 'var(--text-muted)'}}>{cat.count} flips</div>
            </div>
            <div style={{textAlign: 'right'}}>
              <div style={{fontSize: 14, fontWeight: 600, color: cat.avg_profit >= 0 ? 'var(--green)' : 'var(--red)'}}>
                {fmt(cat.avg_profit)}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PlatformPerformance({ platforms }) {
  return (
    <div className="chart-container">
      <div style={{fontSize: 16, fontWeight: 600, marginBottom: 16, color: 'var(--text)'}}>
        Platform Performance
      </div>
      <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
        {platforms.map(platform => (
          <div key={platform.name} style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 12px', background: 'var(--surface)', borderRadius: 8}}>
            <span style={{fontSize: 14, fontWeight: 500, color: 'var(--text)'}}>
              {platform.name === 'Facebook' ? 'Facebook Marketplace' : platform.name}
            </span>
            <span style={{fontSize: 14, fontWeight: 600, color: platform.avg_profit >= 0 ? 'var(--green)' : 'var(--red)'}}>
              {fmt(platform.avg_profit)}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { DesktopDashboard });