// Day-by-day timeline strip — minimal, friendly, glanceable. Each day is a
// small chip with a colored phase dot, weekday + date, and a sleep block bar.
// Selected day is highlighted; details surface in the recommendation card
// + clock above. Optimised to read at a glance even with 15-20 days.

const { useState: useStateTL } = React;
const { fmtHM, hmToMin } = window.JL;

const PHASE_COLOR = {
  'pre-shift':   '#9b8cf0',
  'travel':      '#ffd166',
  'recovery':    '#ff9b50',
  'destination': '#7de696',
};
const PHASE_LABEL = {
  'pre-shift':   'Prep',
  'travel':      'Travel',
  'recovery':    'Recover',
  'destination': 'At dest',
};

function Timeline({ plan, selectedIdx, onSelect }) {
  if (!plan) return null;

  // Group by phase for the legend
  const phasesUsed = [...new Set(plan.days.map(d => d.phase))];

  return (
    <div style={{ padding: '0 28px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 12, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
          <div style={{ fontSize: 11, letterSpacing: '0.3em', color: 'rgba(255,255,255,0.55)',
            textTransform: 'uppercase', fontWeight: 700 }}>
            Your {plan.days.length}-day plan
          </div>
        </div>
        {/* Phase legend */}
        <div style={{ display: 'flex', gap: 14, fontSize: 10, color: 'rgba(255,255,255,0.55)' }}>
          {phasesUsed.map(p => (
            <div key={p} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: PHASE_COLOR[p] }} />
              {PHASE_LABEL[p]}
            </div>
          ))}
        </div>
      </div>

      {/* Horizontal compact chip strip */}
      <div style={{
        display: 'flex', gap: 4, overflowX: 'auto', paddingBottom: 8,
      }}>
        {plan.days.map((d, i) => (
          <DayChip key={i} day={d} idx={i} selected={i === selectedIdx}
            onClick={() => onSelect(i)} />
        ))}
      </div>
    </div>
  );
}

// Compact day chip: just phase color stripe + date + tiny sleep bar.
function DayChip({ day, idx, selected, onClick }) {
  const phaseColor = PHASE_COLOR[day.phase];
  const sleepFrom = hmToMin(day.sleep.start);
  const sleepTo   = hmToMin(day.sleep.end);
  const dateStr = day.date.toLocaleDateString(undefined, { weekday: 'narrow', day: '2-digit' });
  const fullDate = day.date.toLocaleDateString(undefined, { weekday: 'long', month: 'short', day: 'numeric' });

  return (
    <button type="button" onClick={onClick}
      title={`${fullDate} · ${PHASE_LABEL[day.phase]} · sleep ${fmtHM(day.sleep.start)}–${fmtHM(day.sleep.end)}`}
      className={`jl-btn jl-glass-chip${selected ? ' is-selected' : ''}`}
      style={{
        flex: '1 1 0', minWidth: 38,
        borderRadius: 10,
        padding: '8px 4px 6px',
        cursor: 'pointer', textAlign: 'center',
        color: '#fafafa', fontFamily: 'inherit',
        borderColor: selected ? phaseColor : undefined,
        transition: 'border-color .15s, box-shadow .2s, background .15s, transform .15s',
      }}>
      {/* Phase color stripe at top */}
      <div style={{
        position: 'absolute', top: 0, left: 4, right: 4, height: 2,
        background: phaseColor, borderRadius: 99,
        opacity: selected ? 1 : 0.5,
      }} />
      <div style={{ fontSize: 10, color: 'rgba(255,255,255,.5)', fontWeight: 600, lineHeight: 1 }}>
        {dateStr.split(' ')[0]}
      </div>
      <div style={{ fontSize: 14, color: '#fafafa', fontWeight: 600, marginTop: 2, lineHeight: 1,
        fontVariantNumeric: 'tabular-nums' }}>
        {day.date.getDate()}
      </div>
      {/* Sleep mini-bar (24h ribbon) — visualizes when sleep happens */}
      <div style={{ position: 'relative', height: 3, marginTop: 6, marginInline: 2,
        background: 'rgba(255,255,255,0.06)', borderRadius: 2 }}>
        {(() => {
          // Render sleep block; may wrap midnight
          if (sleepFrom <= sleepTo) {
            return (
              <div style={{ position: 'absolute', top: 0, bottom: 0,
                left: `${(sleepFrom / 1440) * 100}%`,
                width: `${((sleepTo - sleepFrom) / 1440) * 100}%`,
                background: phaseColor, opacity: 0.85, borderRadius: 2,
              }} />
            );
          }
          return (
            <React.Fragment>
              <div style={{ position: 'absolute', top: 0, bottom: 0,
                left: `${(sleepFrom / 1440) * 100}%`,
                right: 0, background: phaseColor, opacity: 0.85, borderRadius: 2,
              }} />
              <div style={{ position: 'absolute', top: 0, bottom: 0,
                left: 0, width: `${(sleepTo / 1440) * 100}%`,
                background: phaseColor, opacity: 0.85, borderRadius: 2,
              }} />
            </React.Fragment>
          );
        })()}
      </div>
    </button>
  );
}

window.Timeline = Timeline;
