// The 5 weekly priorities — heart of the app.
// Escalation system: rollovers field drives stage (fresh → rolled → final).
//   fresh  = rollovers 0 — normal state
//   rolled = rollovers 1 — moved from last week, amber/red nudges
//   final  = rollovers 2+ OR extended:true — locked, no more moves
// WeekPressure banner shows urgency based on day of week.

// ── Stage + week-phase helpers ─────────────────────────────────────────────
function getPriorityStage(p) {
  if (p.extended || (p.rollovers || 0) >= 2) return 'final';
  if ((p.rollovers || 0) === 1) return 'rolled';
  return 'fresh';
}

function getWeekPhase() {
  // 0=Sun 1=Mon 2=Tue 3=Wed 4=Thu 5=Fri 6=Sat
  const d = new Date().getDay();
  if (d === 0) return 'closing';
  if (d >= 5) return 'urgent';
  if (d === 4) return 'warming';
  return 'calm';
}

function isWeekEnd() {
  const d = new Date().getDay();
  return d === 5 || d === 6; // Fri or Sat
}

// ── WeekPressure banner ────────────────────────────────────────────────────
function WeekPressure({ priorities }) {
  const phase    = getWeekPhase();
  const DAY_LABELS = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
  // Map JS getDay() (Sun=0) → ribbon index (Mon=0 … Sun=6)
  const dayJs       = new Date().getDay();
  const todayIdx    = dayJs === 0 ? 6 : dayJs - 1;

  const rolled  = priorities.filter(p => getPriorityStage(p) === 'rolled').length;
  const finals  = priorities.filter(p => getPriorityStage(p) === 'final').length;
  const atRisk  = priorities.filter(p => getPriorityStage(p) !== 'final').length;

  const phaseLabel = {
    calm:    '',
    warming: 'THU · WARMING UP',
    urgent:  dayJs === 6 ? 'SAT · LAST CALL' : 'FRI · LAST CHANCE',
    closing: 'SUN · CLOSING TIME',
  }[phase];

  const showAlert = phase !== 'calm' && atRisk > 0;

  return (
    <div className={`mc-weekpress mc-weekpress--${phase}`}>
      {showAlert && (
        <div className="mc-weekpress-left">
          <span className="mc-weekpress-day">{phaseLabel}</span>
          <span className="mc-weekpress-msg">
            {atRisk} {atRisk === 1 ? 'priority' : 'priorities'} roll{atRisk === 1 ? 's' : ''} over if not closed this weekend.
            {rolled > 0 && ` ${rolled} already on borrowed time — finish ${rolled === 1 ? 'it' : 'them'}.`}
          </span>
        </div>
      )}
      <div className={`mc-weekribbon${showAlert ? '' : ' mc-weekribbon--solo'}`}>
        {DAY_LABELS.map((d, i) => (
          <span key={i} className={[
            'mc-weekribbon-day',
            i === todayIdx ? 'today' : '',
            i < todayIdx  ? 'past'  : '',
          ].filter(Boolean).join(' ')}>
            {d}
          </span>
        ))}
        <span className="mc-weekribbon-line">THE LINE ↑</span>
      </div>
    </div>
  );
}

// ── Main Priorities section ────────────────────────────────────────────────
function Priorities() {
  const CAP = 5;
  const { state, toggleTask, addTask, addPriority, renamePriority, transferPriority,
          deletePriority, completePriority, startBurst, startWrap, setPriorityCategory,
          grantExtension } = useStore();

  const handleToggleTask = (priorityId, task) => {
    if (!task.done) {
      toggleTask(priorityId, task.id);
      startWrap(priorityId, task.id);
    } else {
      toggleTask(priorityId, task.id);
    }
  };

  const usedCount = state.priorities.length;
  const pips = Array.from({ length: CAP }, (_, i) => i < usedCount);
  const covered = new Set(state.priorities.map((p) => p.tag));

  return (
    <section className="mc-card mc-prio-hero">
      <div className="head">
        <div>
          <h1>This week</h1>
          <div className="sub">
            Five in the running, max. Complete one to free up a slot — move one to next week, once.
          </div>
        </div>
        <div className="mc-prio-cap">
          {pips.map((on, i) => <span key={i} className={`pip ${on ? 'on' : ''}`}/>)}
          <span style={{ marginLeft: 8 }}>{usedCount}/{CAP}</span>
        </div>
      </div>

      <WeekPressure priorities={state.priorities}/>

      <CoverageStrip covered={covered}/>

      <div className="mc-prio-grid">
        {state.priorities.slice(0, CAP).map((p, idx) => (
          <PriorityCard
            key={p.id} p={p} idx={idx + 1}
            onToggleTask={(task) => handleToggleTask(p.id, task)}
            onAddTask={(label) => addTask(p.id, label)}
            onRename={(t) => renamePriority(p.id, t)}
            onSetCategory={(tag) => setPriorityCategory(p.id, tag)}
            onTransfer={() => transferPriority(p.id)}
            onExtend={() => grantExtension(p.id)}
            onDelete={() => deletePriority(p.id)}
            onComplete={() => completePriority(p.id)}
            onBurst={(tid) => startBurst(p.id, tid, state.burst.length)}
          />
        ))}
        {Array.from({ length: Math.max(0, CAP - usedCount) }, (_, i) => (
          <EmptySlot key={'e' + i} onAdd={addPriority} index={usedCount + i + 1}/>
        ))}
      </div>
    </section>
  );
}

// ── Coverage strip ─────────────────────────────────────────────────────────
function CoverageStrip({ covered }) {
  const missing = CATEGORY_ORDER.filter((k) => !covered.has(k));
  return (
    <div className="mc-coverage">
      <span className="mc-coverage-lbl">Coverage</span>
      <div className="mc-coverage-chips">
        {CATEGORY_ORDER.map((k) => {
          const c = CATEGORIES[k];
          const on = covered.has(k);
          return (
            <span key={k} className={`mc-cov-chip ${on ? 'on' : 'off'}`}
                  style={{ '--cat-color': c.color, '--cat-bg': c.bg, '--cat-fg': c.fg }}>
              <span className="dot"/>{c.label}
            </span>
          );
        })}
      </div>
      {missing.length > 0 && (
        <span className="mc-coverage-hint">
          {missing.length === 5
            ? 'Pick at least one of each for breadth'
            : missing.length === 1
            ? `Missing: ${CATEGORIES[missing[0]].label}`
            : `${missing.length} categories uncovered`}
        </span>
      )}
    </div>
  );
}

// ── Priority card ──────────────────────────────────────────────────────────
function PriorityCard({ p, idx, onToggleTask, onAddTask, onRename, onSetCategory,
                        onTransfer, onExtend, onDelete, onComplete, onBurst }) {
  const done = p.tasks.filter((t) => t.done).length;
  const pct  = p.tasks.length ? Math.round(done / p.tasks.length * 100) : 0;
  const [adding, setAdding]   = React.useState(false);
  const [draft, setDraft]     = React.useState('');
  const [catOpen, setCatOpen] = React.useState(false);
  const [extConfirm, setExtConfirm] = React.useState(false);
  const titleRef = React.useRef(null);

  const stage       = getPriorityStage(p);
  const weekend     = isWeekEnd();
  const canTransfer = stage === 'fresh' && !p.transferred;
  const lastChance  = stage === 'fresh' && weekend;

  const commitTitle = () => {
    const v = titleRef.current?.textContent?.trim();
    if (v && v !== p.title) onRename(v);
  };

  const submitTask = (e) => {
    e?.preventDefault();
    if (draft.trim()) onAddTask(draft.trim());
    setDraft(''); setAdding(false);
  };

  const cat = CATEGORIES[p.tag] || CATEGORIES.ops;

  // Stage-specific tag label
  const stageTag = (() => {
    if (stage === 'final')  return { label: 'final week — no more moves', cls: 'crit' };
    if (stage === 'rolled') return { label: `rolled over · week ${(p.rollovers || 1) + 1}`, cls: 'crit' };
    if (stage === 'fresh' && weekend) return { label: 'last chance — closes tomorrow', cls: 'last' };
    return null;
  })();

  return (
    <article className={`mc-prio stage-${stage}${lastChance ? ' last-chance' : ''}`}>

      {/* ── Top urgency banners ── always visible, can't be missed ── */}
      {lastChance && (
        <div className="mc-urgency mc-urgency--amber">
          <div className="mc-urgency-body">
            <span className="mc-urgency-icon">⚡</span>
            <span>
              <strong>Last chance this week.</strong>{' '}
              {canTransfer
                ? 'Close it this weekend or move it to next week — one free move left.'
                : 'Transfer already used — you must close this or grant an extension.'}
            </span>
          </div>
          {canTransfer && (
            <button className="mc-urgency-btn" onClick={onTransfer}>↪ Move to next week</button>
          )}
        </div>
      )}

      {stage === 'rolled' && (
        <div className="mc-urgency mc-urgency--red">
          <div className="mc-urgency-body">
            <span className="mc-urgency-icon">🔴</span>
            <span>
              <strong>Carried over from last week.</strong>{' '}
              This must close this week — or use a special one-week extension.
            </span>
          </div>
          {!p.extended && !extConfirm && (
            <button className="mc-urgency-btn mc-urgency-btn--ghost" onClick={() => setExtConfirm(true)}>
              + Grant 1-week extension
            </button>
          )}
          {!p.extended && extConfirm && (
            <span className="ext-confirm">
              This is the final extension.{' '}
              <button className="ext-link" onClick={() => { onExtend(); setExtConfirm(false); }}>
                Confirm
              </button>{' · '}
              <button className="ext-link" style={{ opacity: 0.6 }} onClick={() => setExtConfirm(false)}>
                Cancel
              </button>
            </span>
          )}
        </div>
      )}

      {stage === 'final' && (
        <div className="mc-urgency mc-urgency--dark">
          <span className="mc-urgency-icon">🔒</span>
          <span>
            <strong>{p.extended ? 'Special extension week.' : 'Final week.'}</strong>{' '}
            No more moves. Close it or cut it — this is the end of the line.
          </span>
        </div>
      )}

      <div className="mc-prio-top">
        <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', flex: 1, minWidth: 0 }}>
          <div className="mc-prio-num">{idx}</div>
          <h3 className="mc-prio-title"
              ref={titleRef}
              contentEditable
              suppressContentEditableWarning
              spellCheck={false}
              onBlur={commitTitle}
              onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); e.currentTarget.blur(); } }}>
            {p.title}
          </h3>
        </div>
        <div className="mc-prio-actions">
          <button className="mc-iconbtn" title="Complete & log to wins" onClick={onComplete}>
            <Icons.Check size={16}/>
          </button>
          <button className="mc-iconbtn"
                  title={!canTransfer
                    ? (stage !== 'fresh' ? 'No more moves — already rolled over' : 'Transfer already used')
                    : 'Move to next week (one free move)'}
                  disabled={!canTransfer}
                  onClick={onTransfer}>
            <Icons.Repeat size={15}/>
          </button>
          <button className="mc-iconbtn danger" title="Delete" onClick={onDelete}>
            <Icons.Trash size={15}/>
          </button>
        </div>
      </div>

      <div className="mc-prio-tags" style={{ position: 'relative' }}>
        <button className="mc-cat-chip"
                onClick={() => setCatOpen((o) => !o)}
                style={{ '--cat-color': cat.color, '--cat-bg': cat.bg, '--cat-fg': cat.fg }}
                title="Change category">
          <span className="dot"/>{cat.label}
          <Icons.ArrowR size={9} style={{ transform: 'rotate(90deg)', opacity: 0.6 }}/>
        </button>
        {stageTag && (
          <span className={`mc-tag ${stageTag.cls}`}>• {stageTag.label}</span>
        )}
        {catOpen && (
          <div className="mc-cat-menu" onMouseLeave={() => setCatOpen(false)}>
            <div className="mc-cat-menu-hd">Category</div>
            {CATEGORY_ORDER.map((k) => {
              const c = CATEGORIES[k];
              return (
                <button key={k}
                  onClick={() => { onSetCategory(k); setCatOpen(false); }}
                  className={p.tag === k ? 'sel' : ''}
                  style={{ '--cat-color': c.color }}>
                  <span className="dot"/>
                  <span style={{ flex: 1, textAlign: 'left' }}>{c.full}</span>
                  <span className="energy">{c.energyLabel}</span>
                </button>
              );
            })}
          </div>
        )}
      </div>

      <div className="mc-prio-tasks">
        {p.tasks.map((t) => (
          <div key={t.id} className={`mc-task ${t.done ? 'done' : ''}`}
               onClick={() => onToggleTask(t)}>
            <span className="mc-task-check">
              {t.done && <Icons.Check size={11} sw={3}/>}
            </span>
            <span className="mc-task-label">{t.label}</span>
            <span className="mc-task-burst"
                  onClick={(e) => { e.stopPropagation(); onBurst(t.id); }}>
              ⚡ burst
            </span>
          </div>
        ))}

        {adding ? (
          <form onSubmit={submitTask} style={{ display: 'flex', gap: 6, marginTop: 4 }}>
            <input
              autoFocus value={draft}
              onChange={(e) => setDraft(e.target.value)}
              onBlur={submitTask}
              onKeyDown={(e) => { if (e.key === 'Escape') { setAdding(false); setDraft(''); } }}
              placeholder="Next concrete step…"
              style={{
                flex: 1, fontFamily: 'inherit', fontSize: 13, padding: '6px 10px',
                border: '1px solid var(--indigo-300)', borderRadius: 8,
                background: 'var(--bg-elev)', color: 'var(--fg)', outline: 'none',
                boxShadow: 'var(--focus-ring)',
              }}
            />
          </form>
        ) : (
          <button className="mc-add-task" onClick={() => setAdding(true)}>
            <Icons.Plus size={13}/> Add next step
          </button>
        )}
      </div>

      <div className="mc-prio-foot">
        <span className="mc-progress">
          <span className="bar"><i style={{ width: `${pct}%` }}/></span>
          {done}/{p.tasks.length}
        </span>
        <span className={`mc-prio-foot-status stage-${stage}`}>
          {stage === 'final'  ? '🔒 no more moves'           :
           stage === 'rolled' ? '⚠ week 2 — extension available' :
           lastChance         ? '⚡ closes this weekend'      :
           canTransfer        ? 'transfer available'           : 'transfer used'}
        </span>
      </div>
    </article>
  );
}

function EmptySlot({ onAdd, index }) {
  const [adding, setAdding] = React.useState(false);
  const [draft, setDraft]   = React.useState('');
  if (adding) {
    return (
      <form className="mc-prio-empty"
        onSubmit={(e) => { e.preventDefault(); if (draft.trim()) onAdd(draft.trim()); setDraft(''); setAdding(false); }}
        style={{ display: 'block', textAlign: 'left', cursor: 'auto' }}>
        <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase',
          letterSpacing: '0.08em', color: 'var(--indigo-500)', marginBottom: 8 }}>
          Priority #{index}
        </div>
        <input
          autoFocus value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onBlur={() => { if (!draft.trim()) setAdding(false); else { onAdd(draft.trim()); setDraft(''); setAdding(false); } }}
          onKeyDown={(e) => { if (e.key === 'Escape') { setAdding(false); setDraft(''); } }}
          placeholder="One big outcome this week…"
          style={{
            width: '100%', fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: 16, padding: '6px 8px', border: '1px solid var(--indigo-300)',
            borderRadius: 8, background: 'var(--bg-elev)', color: 'var(--fg)',
            outline: 'none', boxShadow: 'var(--focus-ring)',
          }}
        />
      </form>
    );
  }
  return (
    <button className="mc-prio-empty" onClick={() => setAdding(true)}>
      <div>
        <Icons.Plus size={18}/>
        <div style={{ marginTop: 6, fontWeight: 600 }}>Add priority #{index}</div>
        <div style={{ fontSize: 11, marginTop: 2, color: 'var(--fg-muted)' }}>
          One outcome you want closed this week
        </div>
      </div>
    </button>
  );
}

Object.assign(window, { Priorities });
