const { useState: useStateOH, useMemo: useMemoOH } = React;

function OverheadScreen({ navigate }) {
  const { state, dispatch } = useStore();
  const { overhead, flips } = state;

  const [desc, setDesc] = useState('');
  const [amount, setAmount] = useState('');
  const [date, setDate] = useState(todayStr());
  const [category, setCategory] = useState('');

  const sold = flips.filter(f => f.status === 'sold' && f.sell_price != null);
  const grossProfit = sold.reduce((s, f) => s + f.sell_price - f.buy_price - (f.fees||0) - (f.shipping||0), 0);
  const totalOverhead = overhead.reduce((s, o) => s + o.amount, 0);
  const overheadPerFlip = sold.length > 0 ? totalOverhead / sold.length : 0;
  const realProfit = grossProfit - totalOverhead;

  function handleAdd(e) {
    e.preventDefault();
    if (!desc || !amount || !date) return;
    dispatch({ type: 'ADD_OVERHEAD', item: { description: desc, amount: parseFloat(amount), date, category } });
    setDesc(''); setAmount(''); setCategory('');
  }

  function handleDelete(id) {
    if (confirm('Delete this cost?')) dispatch({ type: 'DELETE_OVERHEAD', id });
  }

  return (
    <div className="content">

      {/* Hero — red gradient matching home card */}
      <div style={{
        margin:'8px 16px 0',
        background:'linear-gradient(135deg,#b91c1c,#ef4444)',
        borderRadius:18, padding:'22px 20px',
        position:'relative', overflow:'hidden'
      }}>
        <div style={{position:'absolute',top:-30,right:-20,width:120,height:120,background:'rgba(255,255,255,0.07)',borderRadius:'50%',pointerEvents:'none'}} />
        <div style={{position:'relative'}}>
          <div style={{fontSize:10,color:'rgba(255,255,255,0.65)',textTransform:'uppercase',letterSpacing:'0.6px',fontWeight:700,marginBottom:6}}>Total overhead · {new Date().getFullYear()}</div>
          <div style={{fontSize:40,fontWeight:700,letterSpacing:'-2px',color:'white',marginBottom:4}}>{fmt(totalOverhead, 2)}</div>
          <div style={{fontSize:13,color:'rgba(255,255,255,0.55)',marginBottom:16}}>Across {overhead.length} cost{overhead.length !== 1 ? 's' : ''}</div>
          <div style={{display:'flex', gap:8}}>
            <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}}>Avg cost per flip</div>
              <div style={{fontSize:15,fontWeight:700,color:'white'}}>{fmt(overheadPerFlip, 2)}</div>
            </div>
          </div>
        </div>
      </div>

      <div className="section">
        <div className="section-head"><span className="section-title">Log a cost</span></div>
      </div>

      <div className="form-card">
        <form onSubmit={handleAdd} style={{display:'flex',flexDirection:'column',gap:14}}>
          <div className="form-group">
            <label>Description</label>
            <input type="text" placeholder="e.g. Thermal paste, screwdriver set"
              value={desc} onChange={e => setDesc(e.target.value)} required />
          </div>
          <div className="form-group">
            <label>Amount</label>
            <div className="input-prefix">
              <span>$</span>
              <input type="number" placeholder="0" step="0.01" min="0" inputMode="decimal"
                value={amount} onChange={e => setAmount(e.target.value)} required />
            </div>
          </div>
          <div className="form-row">
            <div className="form-group">
              <label>Date</label>
              <input type="date" value={date} onChange={e => setDate(e.target.value)} required />
            </div>
            <div className="form-group">
              <label>Category <span className="label-hint">(opt)</span></label>
              <input type="text" placeholder="Tools, Supplies..."
                value={category} onChange={e => setCategory(e.target.value)} />
            </div>
          </div>
          <button type="submit" className="log-btn">Add cost</button>
        </form>
      </div>

      {overhead.length > 0 && (
        <>
          <div className="section">
            <div className="section-head"><span className="section-title">All costs</span></div>
          </div>
          <div className="flips-list">
            {overhead.map(item => (
              <div key={item.id} className="flip-item">
                <div className="flip-icon" style={{background:catIconBg('Other'),display:'flex',alignItems:'center',justifyContent:'center',fontSize:22,lineHeight:1}}>💸</div>
                <div className="flip-info">
                  <div className="flip-name">{item.description}</div>
                  <div className="flip-meta">{item.category || 'General'} · {item.date}</div>
                </div>
                <div className="flip-right">
                  <div className="flip-profit fp-neg">-{fmt(item.amount, 2)}</div>
                  <button className="delete-btn" style={{fontSize:11,display:'block',marginTop:2,background:'none',border:'none',cursor:'pointer',padding:0}}
                    onClick={() => handleDelete(item.id)}>delete</button>
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {overhead.length === 0 && (
        <div className="empty-state">
          <p>No costs logged yet.</p>
          <p style={{fontSize:13,color:'var(--text-muted)',marginTop:4}}>Track tools, supplies, and platform fees to see your true profit.</p>
        </div>
      )}

      <div style={{height:8}} />
    </div>
  );
}

Object.assign(window, { OverheadScreen });
