// Today dashboard — hero progress, breakdown, today's log

function TodayHero({ added, natural, goal, palette }) {
  const total = Math.round(added + natural);
  const rawPct = goal > 0 ? added / goal : 0;
  const status = statusColor(rawPct, palette);
  const pct = Math.round(rawPct * 100);

  const numberStyle = {
    fontFamily: 'var(--font-mono)', fontSize: 40, fontWeight: 600,
    color: 'var(--text-1)', letterSpacing: -1.5, lineHeight: 1,
  };
  const labelStyle = {
    fontSize: 11, fontWeight: 500, letterSpacing: 0.4,
    color: 'var(--text-2)', textTransform: 'uppercase',
  };
  const unitStyle = { fontSize: 15, color: 'var(--text-2)', marginLeft: 2 };

  return (
    <div style={{ padding: '6px 4px 4px' }}>
      <div style={{ display: 'flex', gap: 20 }}>
        <div style={{ flex: 1 }}>
          <div style={labelStyle}>Added sugar</div>
          <div style={{ ...numberStyle, marginTop: 6 }}>
            {added}<span style={unitStyle}>g</span>
          </div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={labelStyle}>Total sugar</div>
          <div style={{ ...numberStyle, marginTop: 6 }}>
            {total}<span style={unitStyle}>g</span>
          </div>
        </div>
      </div>

      <div style={{
        marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--border)',
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
      }}>
        <div style={labelStyle}>of {goal}g goal</div>
        <div style={{
          fontFamily: 'var(--font-mono)', fontSize: 34, fontWeight: 600,
          color: status, letterSpacing: -1, lineHeight: 1,
        }}>
          {pct}<span style={{ fontSize: 18 }}>%</span>
        </div>
      </div>
    </div>
  );
}

function TodayScreen({ state, dispatch, palette }) {
  const { log, goal } = state;
  const [selectedEntry, setSelectedEntry] = React.useState(null);
  React.useEffect(() => {
    if (selectedEntry) {
      const fresh = log.find(l => l.id === selectedEntry.id);
      if (!fresh) setSelectedEntry(null);
      else if (fresh !== selectedEntry) setSelectedEntry(fresh);
    }
  }, [log]);
  const totals = log.reduce((a, l) => {
    const qty = Number(l.qty) || 1;
    a.nat += (Number(l.natural_g) || 0) * qty;
    a.add += (Number(l.added_g) || 0) * qty;
    return a;
  }, { nat: 0, add: 0 });
  totals.nat = Math.round(totals.nat);
  totals.add = Math.round(totals.add);
  const total = totals.nat + totals.add;

  const byMeal = { Breakfast: [], Lunch: [], Snack: [], Dinner: [] };
  log.forEach(l => {
    const h = new Date(l.logged_at).getHours();
    const meal = h < 10 ? 'Breakfast' : h < 13 ? 'Lunch' : h < 17 ? 'Snack' : 'Dinner';
    byMeal[meal].push(l);
  });

  return (
    <div style={{ padding: '0 0 120px' }}>
      {/* Header */}
      <div style={{
        padding: '70px 20px 8px',
        display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
      }}>
        <div>
        <div style={{
          fontSize: 12, fontWeight: 500, letterSpacing: 0.4,
          color: 'var(--text-3)', textTransform: 'uppercase',
        }}>Friday · April 17</div>
        <div style={{
          fontSize: 30, fontWeight: 700, color: 'var(--text-1)',
          letterSpacing: -0.8, marginTop: 2,
        }}>Today</div>
        </div>
        <button onClick={() => dispatch({ type: 'nav', screen: 'settings' })} style={{
          width: 40, height: 40, borderRadius: 999,
          background: 'var(--surface-1)', border: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', padding: 0,
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--text-1)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="3"/>
            <path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 01-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/>
          </svg>
        </button>
      </div>

      {/* Hero card */}
      <div style={{
        margin: '12px 16px 0', padding: '20px 20px 8px',
        background: 'var(--surface-1)', borderRadius: 20,
        border: '1px solid var(--border)',
      }}>
        <TodayHero
          added={totals.add}
          natural={totals.nat}
          goal={goal}
          palette={palette}
        />
      </div>

      {/* Stacked composition bar */}
      <div style={{
        margin: '16px 16px 0', padding: '16px 18px',
        background: 'var(--surface-1)', borderRadius: 20,
        border: '1px solid var(--border)',
      }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          fontSize: 13, color: 'var(--text-2)', marginBottom: 10,
        }}>
          <span style={{ fontWeight: 500, color: 'var(--text-1)' }}>Composition</span>
          <span style={{ fontFamily: 'var(--font-mono)' }}>
            {total > 0 ? Math.round(totals.add / total * 100) : 0}% added
          </span>
        </div>
        <div style={{
          height: 10, borderRadius: 5, overflow: 'hidden', display: 'flex',
          background: 'var(--surface-2)',
        }}>
          {total > 0 && (
            <>
              <div style={{
                width: `${totals.nat / total * 100}%`,
                background: palette.natural, height: '100%',
              }}/>
              <div style={{
                width: `${totals.add / total * 100}%`,
                background: palette.added, height: '100%',
              }}/>
            </>
          )}
        </div>
        <div style={{
          display: 'flex', gap: 14, marginTop: 10,
          fontSize: 11, color: 'var(--text-2)',
        }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: palette.natural }}/>
            Natural · from fruit, dairy
          </span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: palette.added }}/>
            Added
          </span>
        </div>
      </div>

      {/* Log by meal */}
      <div style={{ margin: '24px 16px 0' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '0 4px 10px',
        }}>
          <div style={{ fontSize: 17, fontWeight: 600, color: 'var(--text-1)' }}>Log</div>
          <button
            onClick={() => dispatch({ type: 'nav', screen: 'log' })}
            style={{
              display: 'flex', alignItems: 'center', gap: 4,
              padding: '6px 10px', borderRadius: 999,
              background: 'var(--accent)', color: '#fff',
              border: 'none', fontSize: 13, fontWeight: 500, cursor: 'pointer',
              fontFamily: 'inherit',
            }}
          >
            {Icon.plus('#fff')} Add food
          </button>
        </div>

        {Object.entries(byMeal).map(([meal, items]) => items.length === 0 ? null : (
          <div key={meal} style={{
            background: 'var(--surface-1)', borderRadius: 16,
            border: '1px solid var(--border)', marginBottom: 10, overflow: 'hidden',
          }}>
            <div style={{
              padding: '12px 16px 6px',
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            }}>
              <span style={{
                fontSize: 11, fontWeight: 600, letterSpacing: 0.5,
                color: 'var(--text-2)', textTransform: 'uppercase',
              }}>{meal}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-3)' }}>
                {items.reduce((s, l) => {
                  const qty = Number(l.qty) || 1;
                  return s + ((Number(l.natural_g) || 0) + (Number(l.added_g) || 0)) * qty;
                }, 0).toFixed(0)}g sugar
              </span>
            </div>
            {items.map((l, i) => {
              const qty = Number(l.qty) || 1;
              const add = Math.round((Number(l.added_g) || 0) * qty);
              const nat = Math.round((Number(l.natural_g) || 0) * qty);
              const d = new Date(l.logged_at);
              const time = `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
              const cat = l.category || 'Snacks';
              const serving = l.serving || '';
              return (
                <div key={l.id}
                  onClick={() => setSelectedEntry(l)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '10px 16px',
                    borderTop: i === 0 ? 'none' : '1px solid var(--border)',
                    cursor: 'pointer',
                  }}>
                  <FoodBadge cat={cat} palette={palette}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15, color: 'var(--text-1)', fontWeight: 500 }}>
                      {l.food_name}
                    </div>
                    <div style={{
                      fontSize: 12, color: 'var(--text-2)', marginTop: 1,
                      display: 'flex', gap: 8, alignItems: 'center',
                    }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                        {Icon.clock('currentColor')} {time}
                      </span>
                      {serving && <><span>·</span><span>{qty === 1 ? serving : `${qty} × ${serving}`}</span></>}
                    </div>
                  </div>
                  <div style={{ textAlign: 'right', flexShrink: 0 }}>
                    <div style={{
                      fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 600,
                      color: add > 0 ? palette.added : 'var(--text-1)',
                    }}>
                      {add > 0 ? `+${add}` : '0'}<span style={{ fontSize: 11, color: 'var(--text-2)' }}>g add</span>
                    </div>
                    <div style={{
                      fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)', marginTop: 1,
                    }}>{nat}g nat</div>
                  </div>
                </div>
              );
            })}
          </div>
        ))}

        {log.length === 0 && (
          <div style={{
            padding: 40, textAlign: 'center',
            background: 'var(--surface-1)', borderRadius: 16,
            border: '1px dashed var(--border)', color: 'var(--text-2)',
          }}>
            <div style={{ fontSize: 14 }}>No food logged yet today.</div>
            <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 4 }}>
              Tap "Add food" to get started.
            </div>
          </div>
        )}
      </div>

      {selectedEntry && (
        <LogEntrySheet
          entry={selectedEntry}
          palette={palette}
          onClose={() => setSelectedEntry(null)}
          onSave={(qty) => {
            dispatch({ type: 'updateLog', id: selectedEntry.id, qty });
            setSelectedEntry(null);
          }}
          onDelete={() => {
            dispatch({ type: 'deleteLog', id: selectedEntry.id });
            setSelectedEntry(null);
          }}
        />
      )}
    </div>
  );
}

function LogEntrySheet({ entry, palette, onClose, onSave, onDelete }) {
  const initialQty = Number(entry.qty) || 1;
  const [qty, setQty] = React.useState(initialQty);
  const dirty = qty !== initialQty;

  const step = (delta) => {
    const next = Math.round((qty + delta) * 2) / 2;
    setQty(Math.min(20, Math.max(0.5, next)));
  };

  const d = new Date(entry.logged_at);
  const time = `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
  const add = Math.round((Number(entry.added_g) || 0) * qty);
  const nat = Math.round((Number(entry.natural_g) || 0) * qty);
  const fmtQty = qty % 1 === 0 ? String(qty) : qty.toFixed(1);

  return (
    <>
      <div
        onClick={onClose}
        style={{
          position: 'absolute', inset: 0, zIndex: 40,
          background: 'rgba(0,0,0,0.35)',
          animation: 'sheetBackdrop 0.2s ease-out',
        }}
      />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 41,
        background: 'var(--surface-1)',
        borderTopLeftRadius: 22, borderTopRightRadius: 22,
        padding: '10px 20px 28px',
        boxShadow: '0 -8px 30px rgba(0,0,0,0.12)',
        animation: 'sheetSlideUp 0.22s cubic-bezier(.2,.8,.2,1)',
      }}>
        <div style={{
          width: 38, height: 4, borderRadius: 2,
          background: 'var(--text-3)', opacity: 0.4,
          margin: '0 auto 14px',
        }}/>

        <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--text-1)' }}>
          {entry.food_name}
        </div>
        <div style={{
          fontSize: 12, color: 'var(--text-2)', marginTop: 3,
          display: 'flex', gap: 8, alignItems: 'center',
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
            {Icon.clock('currentColor')} {time}
          </span>
          {entry.serving && <><span>·</span><span>{entry.serving}</span></>}
        </div>

        <div style={{
          marginTop: 18, padding: '14px 16px', borderRadius: 14,
          background: 'var(--surface-2)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ flex: 1 }}>
            <div style={{
              fontSize: 11, fontWeight: 500, letterSpacing: 0.4,
              color: 'var(--text-2)', textTransform: 'uppercase',
            }}>Servings</div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 28, fontWeight: 600,
              color: 'var(--text-1)', letterSpacing: -0.5, marginTop: 2,
            }}>{fmtQty}</div>
          </div>
          <button onClick={() => step(-0.5)} disabled={qty <= 0.5} style={stepButton(palette, qty <= 0.5)}>−</button>
          <button onClick={() => step(0.5)}  disabled={qty >= 20}  style={stepButton(palette, qty >= 20)}>+</button>
        </div>

        <div style={{
          marginTop: 10, fontFamily: 'var(--font-mono)', fontSize: 12,
          color: 'var(--text-2)', textAlign: 'right',
        }}>
          {add > 0 && <span style={{ color: palette.added, fontWeight: 600 }}>+{add}g added</span>}
          {add > 0 && nat > 0 && <span> · </span>}
          {nat > 0 && <span>{nat}g natural</span>}
          {add === 0 && nat === 0 && <span>0g sugar</span>}
        </div>

        {dirty && (
          <button onClick={() => onSave(qty)} style={{
            marginTop: 14, width: '100%', padding: '13px 16px',
            borderRadius: 14, background: palette.accent, color: '#fff',
            border: 'none', fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
            cursor: 'pointer',
          }}>Save changes</button>
        )}

        <button onClick={onDelete} style={{
          marginTop: dirty ? 8 : 18, width: '100%', padding: '13px 16px',
          borderRadius: 14, background: palette.red + '15', color: palette.red,
          border: 'none', fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          {Icon.trash(palette.red)} Delete entry
        </button>

        <button onClick={onClose} style={{
          marginTop: 8, width: '100%', padding: '13px 16px',
          borderRadius: 14, background: 'transparent', color: 'var(--text-2)',
          border: 'none', fontFamily: 'inherit', fontSize: 15, fontWeight: 500,
          cursor: 'pointer',
        }}>Cancel</button>
      </div>

      <style>{`
        @keyframes sheetBackdrop { from { opacity: 0; } to { opacity: 1; } }
        @keyframes sheetSlideUp  { from { transform: translateY(100%); } to { transform: translateY(0); } }
      `}</style>
    </>
  );
}

function stepButton(palette, disabled) {
  return {
    width: 40, height: 40, borderRadius: 12,
    background: disabled ? 'var(--surface-1)' : palette.accent + '15',
    color: disabled ? 'var(--text-3)' : palette.accent,
    border: 'none', fontSize: 22, fontWeight: 500,
    cursor: disabled ? 'default' : 'pointer',
    fontFamily: 'inherit', lineHeight: 1,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
}

window.TodayScreen = TodayScreen;
