// Log tab — wired to /api/workout-intention, /api/brain-dump, /api/drinks,
// /api/log-event. All saves call onUpdate to refresh /api/today.

const { api } = window.HC_DATA;

function TimeBtn({ children, selected, onClick, disabled, theme }) {
  const p = theme.palette;
  return (
    <button onClick={onClick} disabled={disabled} style={{
      padding: '9px 13px', fontFamily: 'DM Mono, monospace', fontSize: 12,
      background: selected ? p.text : p.card,
      color: selected ? p.card : p.text,
      border: '1px solid ' + (selected ? p.text : p.border),
      borderRadius: 8, cursor: disabled ? 'default' : 'pointer',
      opacity: disabled ? 0.5 : 1, letterSpacing: 0.2,
    }}>{children}</button>
  );
}

function LogTab({ today, onUpdate }) {
  const theme = window.HC_THEME.useHCTheme();
  const p = theme.palette;
  const d = theme.density;
  const Card = window.HCCard;

  const workoutIntention = today.workout_intention || {};
  const brainDump = today.brain_dump || {};
  const drinksToday = today.drinks_today || {};
  const habits = today.habits || {};
  const training = today.training || {};
  const comeback = !!training.comeback_mode;
  const daysSince = training.days_since_training;

  const [workoutBusy, setWorkoutBusy] = React.useState(false);
  const [brainText, setBrainText] = React.useState('');
  const [drinkText, setDrinkText] = React.useState('');
  const [busy, setBusy] = React.useState({ brain: false, drink: false });

  const [eventOpen, setEventOpen] = React.useState(false);
  const [eventText, setEventText] = React.useState('');
  const [eventSaved, setEventSaved] = React.useState(null);
  const [eventBusy, setEventBusy] = React.useState(false);
  const [habitBusy, setHabitBusy] = React.useState(null);

  async function toggleHabit(key) {
    if (habitBusy) return;
    setHabitBusy(key);
    const undo = !!habits[key];
    try {
      await api('/api/habit', {
        method: 'POST',
        body: JSON.stringify({ habit: key, undo }),
      });
      await onUpdate();
    } catch (e) {
      console.error('habit toggle failed', e);
    } finally { setHabitBusy(null); }
  }

  const txAreaStyle = {
    width: '100%', boxSizing: 'border-box', padding: 10,
    fontFamily: 'DM Sans', fontSize: 14, color: p.text,
    border: `1px solid ${p.border}`, borderRadius: 8,
    resize: 'none', outline: 'none', background: p.inputBg,
  };

  async function setWorkout(time) {
    setWorkoutBusy(true);
    try {
      await api('/api/workout-intention', {
        method: 'POST', body: JSON.stringify({ time }),
      });
      await onUpdate();
    } catch (e) {
      console.error('workout save failed', e);
    } finally { setWorkoutBusy(false); }
  }

  async function saveBrain() {
    const text = brainText.trim();
    if (!text || busy.brain) return;
    setBusy((b) => ({ ...b, brain: true }));
    try {
      await api('/api/brain-dump', { method: 'POST', body: JSON.stringify({ text }) });
      setBrainText('');
      await onUpdate();
    } catch (e) {
      console.error('brain dump save failed', e);
    } finally { setBusy((b) => ({ ...b, brain: false })); }
  }

  async function saveDrink() {
    const text = drinkText.trim();
    if (!text || busy.drink) return;
    setBusy((b) => ({ ...b, drink: true }));
    try {
      await api('/api/drinks', { method: 'POST', body: JSON.stringify({ text }) });
      setDrinkText('');
      await onUpdate();
    } catch (e) {
      console.error('drink save failed', e);
    } finally { setBusy((b) => ({ ...b, drink: false })); }
  }

  async function saveEvent() {
    const label = eventText.trim();
    if (!label || eventBusy) return;
    setEventBusy(true);
    try {
      await api('/api/log-event', { method: 'POST', body: JSON.stringify({ label }) });
      setEventSaved(label);
      setEventOpen(false);
      setEventText('');
    } catch (e) {
      console.error('event save failed', e);
    } finally { setEventBusy(false); }
  }

  const workoutDone = !!workoutIntention.time;
  const brainDone = !!brainDump.done;

  const workoutOptions = comeback
    ? [{ label: 'walk only', value: 'walk' }, { label: 'skip', value: 'skip' }]
    : [
        { label: '17:00', value: '17:00' },
        { label: '17:30', value: '17:30' },
        { label: '18:00', value: '18:00' },
        { label: 'walk', value: 'walk' },
        { label: 'skip', value: 'skip' },
      ];

  return (
    <div style={{ padding: '0 16px 24px', display: 'flex', flexDirection: 'column', gap: d.pageGap }}>

      {comeback && daysSince != null && (
        <div style={{
          background: p.bannerBg, border: `1px solid ${p.bannerBorder}`,
          borderRadius: 10, padding: '10px 14px',
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <div style={{ width: 6, height: 6, borderRadius: '50%', background: p.amber }} />
          <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 12, color: p.bannerText }}>
            day {daysSince} · re-entry when ready
          </div>
        </div>
      )}

      {/* Workout */}
      <Card theme={theme} style={{ padding: d.cardPad }}>
        <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans', marginBottom: 8 }}>Workout</div>
        {workoutDone ? (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 14, color: p.training }}>
              {workoutIntention.time === 'skip' ? 'skip ✓'
                : workoutIntention.time === 'walk' ? 'walk only ✓'
                : `${workoutIntention.time} ✓`}
            </div>
            <button onClick={() => setWorkout('')} disabled={workoutBusy} style={{
              fontFamily: 'DM Sans', fontSize: 12, color: p.accent,
              background: 'transparent', border: 'none',
              cursor: workoutBusy ? 'default' : 'pointer', padding: 0,
              opacity: workoutBusy ? 0.4 : 1,
            }}>change</button>
          </div>
        ) : (
          <>
            <div style={{ fontFamily: 'DM Sans', fontSize: 12, color: p.text2, marginBottom: 12 }}>
              {comeback
                ? 'first session back: 20-min walk, no load'
                : "when's your workout?"}
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {workoutOptions.map((o) => (
                <TimeBtn key={o.value} theme={theme} onClick={() => setWorkout(o.value)}
                         disabled={workoutBusy}>{o.label}</TimeBtn>
              ))}
            </div>
          </>
        )}
      </Card>

      {/* Brain dump */}
      <Card theme={theme} style={{ padding: d.cardPad }}>
        <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans', marginBottom: 10 }}>Brain dump</div>
        {brainDone ? (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ fontFamily: 'DM Sans', fontSize: 14, color: p.text, flex: 1, lineHeight: 1.4 }}>
              {brainDump.text}
            </div>
            <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 11, color: p.training, whiteSpace: 'nowrap' }}>done ✓</div>
          </div>
        ) : (
          <>
            <textarea value={brainText} onChange={(e) => setBrainText(e.target.value)}
                      placeholder="what are you still carrying?" rows={2} style={txAreaStyle} />
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 10 }}>
              <button onClick={saveBrain} disabled={!brainText.trim() || busy.brain} style={{
                padding: '8px 18px', fontFamily: 'DM Sans', fontSize: 13,
                background: brainText.trim() && !busy.brain ? p.accent : p.border,
                color: '#fff', border: 'none', borderRadius: 8,
                cursor: brainText.trim() && !busy.brain ? 'pointer' : 'default', fontWeight: 500,
              }}>{busy.brain ? 'saving…' : 'save'}</button>
            </div>
          </>
        )}
      </Card>

      {/* Drinks — input stays active so multiple entries can be logged
          one by one. Today's entries render above the textarea. */}
      <Card theme={theme} style={{ padding: d.cardPad }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans' }}>Drinks</div>
          {(drinksToday.entries && drinksToday.entries.length > 0) && (
            <div style={{
              fontFamily: 'DM Mono, monospace', fontSize: 11, fontWeight: 500,
              padding: '3px 9px', borderRadius: 999,
              background: (drinksToday.total_units ?? 0) >= 3 ? 'rgba(192,57,43,0.12)' : 'rgba(46,111,173,0.12)',
              color: (drinksToday.total_units ?? 0) >= 3 ? p.warning : p.accent,
              whiteSpace: 'nowrap',
            }}>{drinksToday.total_units ?? 0}u today</div>
          )}
        </div>

        {drinksToday.entries && drinksToday.entries.length > 0 && (
          <div style={{
            display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12,
            paddingBottom: 12, borderBottom: `1px solid ${p.divider}`,
          }}>
            {drinksToday.entries.map((e, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontFamily: 'DM Sans', fontSize: 13, color: p.text, lineHeight: 1.35,
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                  }}>{e.text}</div>
                  {e.breakdown && (
                    <div style={{
                      fontFamily: 'DM Mono, monospace', fontSize: 11,
                      color: p.text3, marginTop: 2, lineHeight: 1.3,
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>{e.breakdown}</div>
                  )}
                </div>
                <div style={{
                  fontFamily: 'DM Mono, monospace', fontSize: 11, color: p.text2,
                  whiteSpace: 'nowrap', flexShrink: 0,
                }}>{e.units ?? 0}u</div>
              </div>
            ))}
          </div>
        )}

        <textarea value={drinkText} onChange={(e) => setDrinkText(e.target.value)}
                  placeholder={drinksToday.entries && drinksToday.entries.length > 0
                    ? 'add another drink…'
                    : '2 glasses of white wine at dinner'}
                  rows={2} style={txAreaStyle} />
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 10 }}>
          <button onClick={saveDrink} disabled={!drinkText.trim() || busy.drink} style={{
            padding: '8px 18px', fontFamily: 'DM Sans', fontSize: 13,
            background: drinkText.trim() && !busy.drink ? p.accent : p.border,
            color: '#fff', border: 'none', borderRadius: 8,
            cursor: drinkText.trim() && !busy.drink ? 'pointer' : 'default', fontWeight: 500,
          }}>{busy.drink ? 'saving…' : 'save'}</button>
        </div>
      </Card>

      {/* Evening habits */}
      <Card theme={theme} style={{ padding: d.cardPad }}>
        <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans', marginBottom: 12 }}>Evening</div>
        <div style={{ display: 'flex', gap: 6 }}>
          {[
            { key: 'supplements', label: 'supps', icon: (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3.5" y="9" width="17" height="6" rx="3" transform="rotate(-30 12 12)" />
                <line x1="9" y1="6.5" x2="14" y2="15" />
              </svg>
            ) },
            { key: 'shower', label: 'shower', icon: (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 3.5C9 8 6.5 11 6.5 14.5a5.5 5.5 0 0 0 11 0C17.5 11 15 8 12 3.5z" />
              </svg>
            ) },
            { key: 'book', label: 'book', icon: (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 4.5h6a2.5 2.5 0 0 1 2.5 2.5v12" />
                <path d="M19 4.5h-6A2.5 2.5 0 0 0 10.5 7v12" />
                <path d="M5 4.5v14h6.5" />
                <path d="M19 4.5v14h-6.5" />
              </svg>
            ) },
            { key: 'lights_off', label: 'lights', icon: (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20.5 14.5A9 9 0 1 1 9.5 3.5 7 7 0 0 0 20.5 14.5z" />
              </svg>
            ) },
          ].map(({ key, label, icon }) => {
            const done = habits[key];
            const isBusy = habitBusy === key;
            return (
              <button key={key} onClick={() => toggleHabit(key)} disabled={isBusy} style={{
                flex: 1, padding: '14px 6px 10px',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                background: done ? 'rgba(58,125,92,0.06)' : p.inputBg,
                border: `1px solid ${done ? 'rgba(58,125,92,0.45)' : p.border}`,
                borderRadius: 10, cursor: isBusy ? 'wait' : 'pointer',
                color: done ? p.training : p.text3,
                opacity: isBusy ? 0.6 : 1,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{icon}</div>
                <div style={{ fontFamily: 'DM Sans', fontSize: 11, letterSpacing: 0.6,
                              textTransform: 'uppercase', fontWeight: 500 }}>{label}</div>
                <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 11,
                              color: done ? p.training : 'transparent',
                              minHeight: 14, lineHeight: 1 }}>
                  {done || '·'}
                </div>
              </button>
            );
          })}
        </div>
      </Card>

      {/* Subtle event log */}
      {eventSaved ? (
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '6px 4px', gap: 10,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, minWidth: 0 }}>
            <div style={{ width: 4, height: 4, borderRadius: '50%', background: p.text3, flexShrink: 0 }} />
            <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 11, color: p.text2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              event · {eventSaved}
            </div>
          </div>
          <button onClick={() => { setEventSaved(null); setEventText(''); setEventOpen(true); }} style={{
            fontFamily: 'DM Sans', fontSize: 11, color: p.text3,
            background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
          }}>edit</button>
        </div>
      ) : eventOpen ? (
        <div style={{ padding: '4px 2px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <textarea value={eventText} onChange={(e) => setEventText(e.target.value)}
                    placeholder="back spasm, travel week, new protocol…" rows={2}
                    autoFocus style={{ ...txAreaStyle, fontSize: 13 }} />
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <button onClick={() => { setEventOpen(false); setEventText(''); }} style={{
              padding: '6px 12px', fontFamily: 'DM Sans', fontSize: 12,
              background: 'transparent', color: p.text2,
              border: 'none', borderRadius: 8, cursor: 'pointer',
            }}>cancel</button>
            <button onClick={saveEvent} disabled={!eventText.trim() || eventBusy} style={{
              padding: '6px 14px', fontFamily: 'DM Sans', fontSize: 12,
              background: eventText.trim() && !eventBusy ? p.accent : p.border,
              color: '#fff', border: 'none', borderRadius: 8,
              cursor: eventText.trim() && !eventBusy ? 'pointer' : 'default', fontWeight: 500,
            }}>{eventBusy ? 'saving…' : 'save'}</button>
          </div>
        </div>
      ) : (
        <div style={{ textAlign: 'center', padding: '2px 0' }}>
          <button onClick={() => setEventOpen(true)} style={{
            fontFamily: 'DM Sans', fontSize: 12, color: p.text3,
            background: 'transparent', border: 'none', cursor: 'pointer',
            padding: '4px 6px', letterSpacing: 0.1,
            borderBottom: `1px dashed ${p.border}`, borderRadius: 0,
          }}>log an event</button>
        </div>
      )}

      {(today.nudges && today.nudges.length > 0) && (
        <Card theme={theme} style={{ padding: d.cardPad }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
            <div style={{ fontSize: 10, letterSpacing: 0.6, color: p.text2, textTransform: 'uppercase', fontFamily: 'DM Sans' }}>
              Upcoming
            </div>
            <div style={{ fontFamily: 'DM Mono, monospace', fontSize: 10, color: p.text3 }}>
              next 18h
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {today.nudges.map((n, i) => (
              <div key={`${n.id}-${i}`} style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                <span style={{
                  fontFamily: 'DM Mono, monospace', fontSize: 12,
                  color: p.text, minWidth: 44, letterSpacing: 0.2,
                }}>{n.fire_time}</span>
                <span style={{
                  flex: 1, minWidth: 0, fontFamily: 'DM Sans', fontSize: 13,
                  color: p.text2, overflow: 'hidden', textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}>{n.label}</span>
                <span style={{
                  fontFamily: 'DM Mono, monospace', fontSize: 10,
                  color: n.channel === 'push' ? p.accent
                        : n.channel === 'tg' ? p.text3
                        : p.text3,
                  textTransform: 'uppercase', letterSpacing: 0.4,
                  flexShrink: 0,
                }}>{n.channel}</span>
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}

window.LogTab = LogTab;
