/* Dump — anchors.jsx: the "shape of your day" setup screen.
   Anchors are the fixed real-life blocks (school run, work, bedtime)
   that the calendar reads to show how much time is actually free.
   This is the one place to add / edit / remove them. Reached from the
   Calendar header, the first-visit prompt, and Settings. */

const ANCH_DAYS = [
  { v: 1, l: 'M' }, { v: 2, l: 'T' }, { v: 3, l: 'W' }, { v: 4, l: 'T' },
  { v: 5, l: 'F' }, { v: 6, l: 'S' }, { v: 0, l: 'S' }
];
const ANCH_WEEKDAYS = [1, 2, 3, 4, 5];
const ANCH_EVERYDAY = [1, 2, 3, 4, 5, 6, 0];

function anchEndLabel(time, duration) {
  const start = hmToMin(time);
  if (start == null) return '';
  return minToHm(Math.min(start + (duration || 0), 1439));
}
function daysSummary(days) {
  const set = (days || []).slice().sort();
  const eq = (a) => a.length === set.length && a.every((v) => set.includes(v));
  if (eq(ANCH_WEEKDAYS)) return 'Weekdays';
  if (eq(ANCH_EVERYDAY)) return 'Every day';
  if (eq([6, 0])) return 'Weekends';
  if (set.length === 0) return 'No days yet';
  const names = { 0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat' };
  return [1, 2, 3, 4, 5, 6, 0].filter((d) => set.includes(d)).map((d) => names[d]).join(', ');
}

function AnchorRow({ anchor, onChange, onRemove }) {
  const dur = anchor.duration || 30;
  const setDays = (v) => {
    const has = (anchor.days || []).includes(v);
    onChange({ days: has ? anchor.days.filter((x) => x !== v) : (anchor.days || []).concat([v]) });
  };
  return (
    <div className="anchor-row">
      <div className="anchor-row-main">
        <input className="anchor-name" value={anchor.name} placeholder="Name this block…"
          onChange={(e) => onChange({ name: e.target.value })} />
        <button className="anchor-remove" onClick={onRemove} aria-label="Remove anchor">{Icons.trash(16)}</button>
      </div>
      <div className="anchor-row-controls">
        <div className="anchor-field">
          <label>Starts</label>
          <input type="time" value={anchor.time} onChange={(e) => onChange({ time: e.target.value })} />
        </div>
        <div className="anchor-field">
          <label>Ends</label>
          <input type="time" value={anchEndLabel(anchor.time, dur)}
            onChange={(e) => {
              const s = hmToMin(anchor.time);
              const en = hmToMin(e.target.value);
              if (s == null || en == null || en <= s) return;
              onChange({ duration: Math.min(720, en - s) });
            }} />
        </div>
        <div className="anchor-field anchor-field-end">
          <label>Length</label>
          <span className="anchor-end">{dur >= 60 ? Math.floor(dur / 60) + 'h' + (dur % 60 ? ' ' + (dur % 60) + 'm' : '') : dur + ' min'}</span>
        </div>
      </div>
      <div className="anchor-days">
        <div className="anchor-daypills">
          {ANCH_DAYS.map((d, i) => (
            <button key={i} className={'daypill' + ((anchor.days || []).includes(d.v) ? ' on' : '')}
              onClick={() => setDays(d.v)} title={daysSummary([d.v])}>{d.l}</button>
          ))}
        </div>
        <div className="anchor-daypresets">
          <button className="linklike" onClick={() => onChange({ days: ANCH_WEEKDAYS.slice() })}>Weekdays</button>
          <button className="linklike" onClick={() => onChange({ days: ANCH_EVERYDAY.slice() })}>Every day</button>
        </div>
      </div>
    </div>
  );
}

function AnchorsSection() {
  const { anchors, settings } = useDumpStore();
  const list = anchors || [];

  const update = (id, patch) => DumpStore.set((s) => ({
    anchors: (s.anchors || []).map((a) => a.id === id ? Object.assign({}, a, patch) : a)
  }));
  const remove = (id) => DumpStore.set((s) => ({ anchors: (s.anchors || []).filter((a) => a.id !== id) }));
  const add = () => {
    const a = { id: DumpUtil.uid(), name: '', time: '09:00', duration: 60, days: ANCH_WEEKDAYS.slice() };
    DumpStore.set((s) => ({ anchors: (s.anchors || []).concat([a]) }));
  };
  const resetDefaults = () => {
    if (window.confirm('Replace your anchors with the starter set (school run, work, pickup, bedtime)?')) {
      DumpStore.set({ anchors: DumpUtil.defaultAnchors() });
    }
  };
  const done = () => {
    DumpAPI.dismissHint('anchors-intro');
    DumpStore.set({ route: 'calendar' });
    DumpAPI.toast('Anchors saved — your calendar knows the shape of your week.');
  };

  // a representative weekday for the live preview
  const previewDate = (() => { const d = new Date(); d.setHours(12, 0, 0, 0); while (d.getDay() === 0 || d.getDay() === 6) d.setDate(d.getDate() + 1); return d; })();
  const dayAnchors = anchorsForDay(list, previewDate);
  const cap = dayCapacity(previewDate, [], list, calRange(settings.dx));
  const freeHrs = Math.round((cap.free / 60) * 2) / 2;

  return (
    <div className="section anchors-section" data-screen-label="Anchors">
      <div className="anchors-head">
        <button className="cald-back" onClick={() => DumpStore.set({ route: 'calendar' })}>{Icons.chevL(17)} Calendar</button>
      </div>
      <h1 className="section-title">The shape of your day</h1>
      <p className="section-sub anchors-sub">
        Anchors are the fixed parts of real life — the school run, work hours, dinner and bedtime. They aren’t tasks and you won’t tick them off. Enstow reads them so the calendar can show how much time you <em>actually</em> have, and never pretends a packed Tuesday is wide open.
      </p>

      <div className="anchors-layout">
        <div className="anchors-list">
          {list.length === 0 ? (
            <div className="anchors-empty">
              <p>No anchors yet. Add the blocks that repeat most weeks.</p>
            </div>
          ) : list.map((a) => (
            <AnchorRow key={a.id} anchor={a} onChange={(p) => update(a.id, p)} onRemove={() => remove(a.id)} />
          ))}

          <div className="anchors-actions">
            <button className="btn anchors-add" onClick={add}>+ Add an anchor</button>
            <button className="linklike" onClick={resetDefaults}>Use starter set</button>
          </div>
        </div>

        <aside className="anchors-preview">
          <div className="anchors-preview-card">
            <span className="anchors-preview-label">A typical weekday</span>
            <p className="anchors-preview-free"><strong>≈ {freeHrs} hr{freeHrs === 1 ? '' : 's'} free</strong></p>
            <div className="anchors-preview-list">
              {dayAnchors.length === 0
                ? <span className="anchors-preview-empty">Add anchors to see your day take shape.</span>
                : dayAnchors.map((a, i) => (
                  <div className="anchors-preview-item" key={i}>
                    <span className="apv-time">{minToHm(a.start)}</span>
                    <span className="apv-bar"></span>
                    <span className="apv-name">{a.name || 'Untitled'}</span>
                  </div>
                ))}
            </div>
            <div className="anchors-preview-cap">
              <CapacityBar frac={cap.frac} level={cap.level} style={(settings.dx && settings.dx.capacity) || 'segments'} />
              <span className="apc-label">{Math.round(cap.frac * 100)}% committed before any tasks</span>
            </div>
          </div>
          <p className="anchors-preview-note">{Icons.sparkle(13)} Tip: don’t over-anchor. Block the things that are genuinely fixed — leave the rest free so tasks have somewhere to land.</p>
        </aside>
      </div>

      <div className="anchors-foot">
        <button className="btn btn-primary" onClick={done}>Done</button>
      </div>
    </div>
  );
}

window.AnchorsSection = AnchorsSection;
