
// DraftSimulator.jsx — Cozy Board Game
const { useState, useEffect, useMemo, useRef } = React;
const { useApp } = window;

(() => {
  if (document.getElementById('draft-simulator-css')) return;
  const s = document.createElement('style');
  s.id = 'draft-simulator-css';
  s.textContent = `
    @keyframes cozy-puff {
      0% { transform: scale(1); opacity: 0.85; }
      100% { transform: scale(1.45); opacity: 0; filter: blur(2px); }
    }
    .cozy-puff-anim {
      animation: cozy-puff 0.48s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
      pointer-events: none;
    }
    @keyframes ft-glow {
      0%, 100% { box-shadow: 0 0 0 0px var(--accent-orange); }
      50% { box-shadow: 0 0 0 6px rgba(196, 132, 90, 0); }
    }
    .ft-glow-active {
      animation: ft-glow 1.5s infinite;
      border-color: var(--accent-orange) !important;
      position: relative;
    }
    .ft-undo-overlay {
      position: absolute;
      inset: 0;
      background: rgba(232, 85, 85, 0.4);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.2s ease-in-out;
      cursor: pointer;
      z-index: 10;
    }
    .ft-undo-overlay:hover {
      opacity: 1;
    }
  `;
  document.head.appendChild(s);
})();


// Persisted saved-scenarios store. Each scenario carries the bans + picks plus
// a comment thread the whole crew can leave notes on.
const SCENARIOS_KEY = 'cozydraft-draftscenarios-v1';
function loadScenarios() {
  try {
    const raw = localStorage.getItem(SCENARIOS_KEY);
    if (raw) return JSON.parse(raw);
  } catch {}
  return [];
}
function saveScenarios(arr) {
  try { localStorage.setItem(SCENARIOS_KEY, JSON.stringify(arr)); } catch {}
}

// Draft sequence: each step is { team, action, slot }
const DRAFT_SEQUENCE = [
  // Phase 1: First 3 bans alternating (Blue starts)
  { team: 'blue', action: 'ban', slot: 0 },
  { team: 'red',  action: 'ban', slot: 0 },
  { team: 'blue', action: 'ban', slot: 1 },
  { team: 'red',  action: 'ban', slot: 1 },
  { team: 'blue', action: 'ban', slot: 2 },
  { team: 'red',  action: 'ban', slot: 2 },

  // Phase 2: First 6 picks (1-2-2-1)
  { team: 'blue', action: 'pick', slot: 0 }, // B1
  { team: 'red',  action: 'pick', slot: 0 }, // R1
  { team: 'red',  action: 'pick', slot: 1 }, // R2
  { team: 'blue', action: 'pick', slot: 1 }, // B2
  { team: 'blue', action: 'pick', slot: 2 }, // B3
  { team: 'red',  action: 'pick', slot: 2 }, // R3

  // Phase 3: Last 2 bans each, Red starts this phase
  { team: 'red',  action: 'ban', slot: 3 },
  { team: 'blue', action: 'ban', slot: 3 },
  { team: 'red',  action: 'ban', slot: 4 },
  { team: 'blue', action: 'ban', slot: 4 },

  // Phase 4: Last 4 picks (1-2-1)
  { team: 'red',  action: 'pick', slot: 3 }, // R4
  { team: 'blue', action: 'pick', slot: 3 }, // B4
  { team: 'blue', action: 'pick', slot: 4 }, // B5
  { team: 'red',  action: 'pick', slot: 4 }, // R5
];
window.DRAFT_SEQUENCE = DRAFT_SEQUENCE;

function getDraftStepKey(step) {
  const prefix = step.team === 'blue' ? 'B' : 'R';
  if (step.action === 'ban') {
    return `${prefix}B${step.slot + 1}`;
  } else {
    return `${prefix}${step.slot + 1}`;
  }
}
window.getDraftStepKey = getDraftStepKey;

const LIVE_DRAFT_KEY = 'cozydraft-live-draft-progress';

function loadActiveDraft() {
  try {
    const raw = localStorage.getItem(LIVE_DRAFT_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      if (parsed && typeof parsed.step === 'number') return parsed;
    }
  } catch {}
  return EMPTY_STATE;
}

window.isLiveDraftInProgress = function() {
  if (window._liveDraftInProgress) return true;
  try {
    const raw = localStorage.getItem(LIVE_DRAFT_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      if (parsed && parsed.step > 0 && parsed.step < 20) return true;
    }
  } catch {}
  return false;
};

function getDraftPhase(step) {
  if (step < 6) return 'Ban Phase 1 ⚔️';
  if (step < 12) return 'Pick Phase 1 🌸';
  if (step < 16) return 'Ban Phase 2 ⚔️';
  return 'Pick Phase 2 🌸';
}


const EMPTY_STATE = {
  blueBans: Array(5).fill(null),
  redBans: Array(5).fill(null),
  bluePicks: Array(5).fill(null),
  redPicks: Array(5).fill(null),
  step: 0,
  search: '',
};

function DraftSimulator() {
  const { champions, championsLoading, showToast } = useApp();
  const [draft, setDraft] = useState(loadActiveDraft);

  useEffect(() => {
    const isProgress = draft.step > 0 && draft.step < DRAFT_SEQUENCE.length;
    window._liveDraftInProgress = isProgress;
    try {
      if (isProgress) {
        localStorage.setItem(LIVE_DRAFT_KEY, JSON.stringify(draft));
      } else {
        localStorage.removeItem(LIVE_DRAFT_KEY);
      }
    } catch (e) {}
  }, [draft]);
  const [search, setSearch] = useState('');

  // ── Saved scenarios state ────────────────────────────────────────────────
  const [scenarios, setScenarios] = useState(loadScenarios);
  const [showSavePrompt, setShowSavePrompt] = useState(false);
  const [nameDraft, setNameDraft] = useState('');
  const [expanded, setExpanded] = useState(null);

  const [puffing, setPuffing] = useState(null); // { side, action, slot, championId }
  const [confirmUndoData, setConfirmUndoData] = useState(null); // { targetStepIndex, championName }

  const lastAction = draft.step > 0 ? DRAFT_SEQUENCE[draft.step - 1] : null;
  const isMostRecentSlot = (side, action, slot) => {
    return lastAction && lastAction.team === side && lastAction.action === action && lastAction.slot === slot;
  };

  const undoLastStep = () => {
    if (draft.step === 0) return;
    const previousStep = draft.step - 1;
    const previousAction = DRAFT_SEQUENCE[previousStep];
    const { team, action, slot } = previousAction;

    // Get the champion currently in the slot we are about to clear
    const championId = team === 'blue'
      ? (action === 'ban' ? draft.blueBans[slot] : draft.bluePicks[slot])
      : (action === 'ban' ? draft.redBans[slot] : draft.redPicks[slot]);

    if (championId) {
      setPuffing({ side: team, action, slot, championId });
      setTimeout(() => setPuffing(null), 500);
    }

    setDraft(prev => {
      const next = { ...prev };
      if (action === 'ban') {
        if (team === 'blue') {
          next.blueBans = [...prev.blueBans];
          next.blueBans[slot] = null;
        } else {
          next.redBans = [...prev.redBans];
          next.redBans[slot] = null;
        }
      } else {
        if (team === 'blue') {
          next.bluePicks = [...prev.bluePicks];
          next.bluePicks[slot] = null;
        } else {
          next.redPicks = [...prev.redPicks];
          next.redPicks[slot] = null;
        }
      }
      next.step = previousStep;
      return next;
    });

    showToast && showToast('Removed last pick — re-pick this slot ↺');
  };

  const undoToStep = (targetStep) => {
    if (targetStep < 0 || targetStep >= draft.step) return;

    // Get target action details
    const targetAction = DRAFT_SEQUENCE[targetStep];
    const targetChamp = targetAction.team === 'blue'
      ? (targetAction.action === 'ban' ? draft.blueBans[targetAction.slot] : draft.bluePicks[targetAction.slot])
      : (targetAction.action === 'ban' ? draft.redBans[targetAction.slot] : draft.redPicks[targetAction.slot]);

    if (targetChamp) {
      setPuffing({
        side: targetAction.team,
        action: targetAction.action,
        slot: targetAction.slot,
        championId: targetChamp
      });
      setTimeout(() => setPuffing(null), 500);
    }

    setDraft(prev => {
      const next = { ...prev };
      for (let s = prev.step - 1; s >= targetStep; s--) {
        const actionInfo = DRAFT_SEQUENCE[s];
        const { team, action, slot } = actionInfo;
        if (action === 'ban') {
          if (team === 'blue') {
            next.blueBans = [...next.blueBans];
            next.blueBans[slot] = null;
          } else {
            next.redBans = [...next.redBans];
            next.redBans[slot] = null;
          }
        } else {
          if (team === 'blue') {
            next.bluePicks = [...next.bluePicks];
            next.bluePicks[slot] = null;
          } else {
            next.redPicks = [...next.redPicks];
            next.redPicks[slot] = null;
          }
        }
      }
      next.step = targetStep;
      return next;
    });

    showToast && showToast('Rolled back draft status ↺');
  };

  const handleSlotClick = (side, action, slotIndex, championId) => {
    const targetStepIndex = DRAFT_SEQUENCE.findIndex(
      step => step.team === side && step.action === action && step.slot === slotIndex
    );
    if (targetStepIndex === -1 || targetStepIndex >= draft.step) return;

    if (targetStepIndex === draft.step - 1) {
      undoLastStep();
    } else {
      const cd = champions[championId];
      setConfirmUndoData({
        targetStepIndex,
        championName: cd?.name || championId
      });
    }
  };

  // Keyboard shortcut listener
  const undoLastStepRef = useRef(undoLastStep);
  useEffect(() => {
    undoLastStepRef.current = undoLastStep;
  });

  useEffect(() => {
    const handleKeyDown = (e) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
        e.preventDefault();
        undoLastStepRef.current();
      }
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  useEffect(() => { saveScenarios(scenarios); }, [scenarios]);


  const allBanned = [...draft.blueBans, ...draft.redBans].filter(Boolean);
  const allPicked = [...draft.bluePicks, ...draft.redPicks].filter(Boolean);
  const usedChamps = new Set([...allBanned, ...allPicked]);

  const champList = useMemo(() => {
    return Object.values(champions)
      .filter(c => !usedChamps.has(c.id))
      .filter(c => (window.matchesChampionSearch ? window.matchesChampionSearch(c, search) : (!search || c.name.toLowerCase().includes(search.toLowerCase()))))
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [champions, usedChamps, search]);

  const isDone = draft.step >= DRAFT_SEQUENCE.length;
  const currentStep = isDone ? null : DRAFT_SEQUENCE[draft.step];

  const handlePick = (champId) => {
    if (isDone) return;
    const { team, action, slot } = currentStep;
    setDraft(prev => {
      const next = { ...prev };
      if (action === 'ban') {
        if (team === 'blue') {
          next.blueBans = [...prev.blueBans];
          next.blueBans[slot] = champId;
        } else {
          next.redBans = [...prev.redBans];
          next.redBans[slot] = champId;
        }
      } else {
        if (team === 'blue') {
          next.bluePicks = [...prev.bluePicks];
          next.bluePicks[slot] = champId;
        } else {
          next.redPicks = [...prev.redPicks];
          next.redPicks[slot] = champId;
        }
      }
      next.step = prev.step + 1;
      return next;
    });
  };

  const reset = () => {
    try { localStorage.removeItem(LIVE_DRAFT_KEY); } catch (e) {}
    window._liveDraftInProgress = false;
    setDraft(EMPTY_STATE);
    setSearch('');
  };

  // ── Save / load / delete scenarios ───────────────────────────────────────
  const hasAnyPicks = [...draft.blueBans, ...draft.redBans, ...draft.bluePicks, ...draft.redPicks].some(Boolean);

  const openSavePrompt = () => {
    if (!hasAnyPicks) {
      showToast && showToast('Draft something first 🌱');
      return;
    }
    const defaultName = isDone ? `Draft — ${new Date().toLocaleString([], { dateStyle: 'short', timeStyle: 'short' })}`
                               : `Draft (step ${draft.step + 1}) — ${new Date().toLocaleDateString()}`;
    setNameDraft(defaultName);
    setShowSavePrompt(true);
  };

  const commitSave = () => {
    const name = (nameDraft || '').trim() || 'Unnamed scenario';
    const scenario = {
      id: Date.now(),
      name,
      savedAt: new Date().toISOString(),
      step: draft.step,
      blueBans: draft.blueBans,
      redBans:  draft.redBans,
      bluePicks: draft.bluePicks,
      redPicks:  draft.redPicks,
      notes: [],
    };
    setScenarios(prev => [scenario, ...prev].slice(0, 30));
    setShowSavePrompt(false);
    setExpanded(scenario.id);
    showToast && showToast('Scenario saved 📦✨');
  };

  const loadScenario = (sc) => {
    setDraft({
      blueBans: sc.blueBans  || Array(5).fill(null),
      redBans:  sc.redBans   || Array(5).fill(null),
      bluePicks: sc.bluePicks || Array(5).fill(null),
      redPicks:  sc.redPicks  || Array(5).fill(null),
      step: sc.step ?? DRAFT_SEQUENCE.length,
      search: '',
    });
    setSearch('');
    showToast && showToast(`Loaded “${sc.name}” 🎲`);
    if (typeof window !== 'undefined') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const deleteScenario = (id) => {
    const sc = scenarios.find(s => s.id === id);
    if (!sc) return;
    if (!window.confirm(`Delete “${sc.name}”? This can’t be undone.`)) return;
    setScenarios(prev => prev.filter(s => s.id !== id));
    if (expanded === id) setExpanded(null);
    showToast && showToast('Scenario deleted 👋');
  };

  const renameScenario = (id, name) => {
    setScenarios(prev => prev.map(s => s.id === id ? { ...s, name } : s));
  };

  // Comment-thread callbacks bound to a specific scenario id.
  const addNote    = (id, note) => setScenarios(prev => prev.map(s => s.id === id ? { ...s, notes: [...(s.notes || []), note] } : s));
  const editNote   = (id, noteId, text) => setScenarios(prev => prev.map(s =>
    s.id === id ? { ...s, notes: (s.notes || []).map(n => n.id === noteId ? { ...n, text, editedAt: new Date().toISOString() } : n) } : s));
  const deleteNote = (id, noteId) => setScenarios(prev => prev.map(s =>
    s.id === id ? { ...s, notes: (s.notes || []).filter(n => n.id !== noteId) } : s));

  if (championsLoading) return <window.LoadingSpinner />;

  const turnLabel = isDone
    ? '🎉 Draft complete!'
    : `${currentStep.team === 'blue' ? '🌿 Blue' : '🌸 Red'} ${currentStep.action === 'ban' ? 'bans' : 'picks'}!`;

  const turnColor = isDone ? '#7CBF8E' : currentStep.team === 'blue' ? '#7CBF8E' : '#F2A7C3';

  const activePhaseIndex = isDone ? -1 : (
    draft.step < 6 ? 0 :
    draft.step < 12 ? 1 :
    draft.step < 16 ? 2 : 3
  );

  return (
    <div style={{ padding: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, margin: 0 }}>Draft Simulator 🎲</h1>
          <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '4px 0 0 0' }}>
            Tournament draft order — 5 bans each, 5 picks each
          </p>
        </div>
        <div style={{ display: 'inline-flex', gap: 8 }}>
          <window.CozyButton color="terracotta" onClick={openSavePrompt}>
            💾 Save scenario
          </window.CozyButton>
          <window.CozyButton color="cream" onClick={reset}>Reset game 🔄</window.CozyButton>
        </div>
      </div>

      {/* Visual Phase Progress */}
      <div style={{
        display: 'flex', justifyContent: 'center', alignItems: 'center',
        gap: 12, marginBottom: 20, flexWrap: 'wrap'
      }}>
        {[
          { label: 'Ban Phase 1', icon: '⚔️', color: '#7CBF8E' },
          { label: 'Pick Phase 1', icon: '🌸', color: '#7CBF8E' },
          { label: 'Ban Phase 2', icon: '⚔️', color: '#F2A7C3' },
          { label: 'Pick Phase 2', icon: '🌸', color: '#F2A7C3' }
        ].map((phase, idx) => {
          const isActive = idx === activePhaseIndex;
          const isPast = idx < activePhaseIndex;
          return (
            <div
              key={idx}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 6,
                padding: '6px 12px',
                borderRadius: 999,
                background: isActive ? 'var(--surface-card)' : 'rgba(255, 251, 245, 0.5)',
                border: isActive ? `2px solid ${phase.color}` : '2.5px dashed var(--border-default)',
                opacity: isActive ? 1 : isPast ? 0.75 : 0.45,
                boxShadow: isActive ? `0 0 12px ${phase.color}60` : 'none',
                transition: 'all 0.3s ease',
              }}
              title={phase.label}
            >
              <div style={{
                width: 10,
                height: 10,
                borderRadius: '50%',
                background: isActive || isPast ? phase.color : 'var(--border-default)',
                boxShadow: isActive ? `0 0 8px ${phase.color}` : 'none',
                transition: 'all 0.3s ease',
              }} />
              <span className="fredoka" style={{
                fontSize: 12,
                color: isActive ? 'var(--text-primary)' : isPast ? 'var(--accent-orange)' : 'var(--text-muted)',
                fontWeight: isActive ? 800 : 700,
              }}>
                {phase.icon} {phase.label}
              </span>
            </div>
          );
        })}
      </div>

      {/* Turn indicator */}
      <div style={{
        background: 'var(--surface-card)', border: `2.5px solid ${turnColor}`,
        borderRadius: 20, padding: '12px 24px', marginBottom: 20,
        textAlign: 'center', boxShadow: `0 4px 0 ${turnColor}60`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap', gap: 12 }}>
          <span className="fredoka" style={{ fontSize: 22, color: turnColor }}>
            {isDone ? '' : '→ '}
            {turnLabel}
          </span>
          {!isDone && (
            <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-muted)' }}>
              Pick/Ban {draft.step + 1} of 20 · {getDraftPhase(draft.step)}
            </span>
          )}
          <window.CozyButton
            color="cream"
            small
            disabled={draft.step === 0}
            onClick={undoLastStep}
            style={{
              background: draft.step === 0 ? '#E6E1DA' : undefined,
              color: draft.step === 0 ? '#9E948A' : undefined,
              boxShadow: draft.step === 0 ? '0 3px 0 #bdafa2' : undefined,
              border: draft.step === 0 ? '2px solid #bdafa2' : undefined,
              marginLeft: 12
            }}
          >
            ↺ Undo last
          </window.CozyButton>
        </div>
        {!isDone && currentStep.action === 'ban' && (
          <div style={{
            marginTop: 6, fontSize: 13, fontWeight: 800, color: 'var(--text-muted)',
            fontFamily: 'Nunito', letterSpacing: 0.5
          }}>
            Captain's call! 🛡️
          </div>
        )}
      </div>

      {/* Two sides */}
      <div className="responsive-two-column" style={{ marginBottom: 20 }}>
        {/* Blue side */}
        <DraftSide
          label="Our Crew 🌿"
          color="#7CBF8E"
          side="blue"
          bans={draft.blueBans}
          picks={draft.bluePicks}
          isActive={!isDone && currentStep.team === 'blue'}
          puffing={puffing}
          isMostRecentSlot={isMostRecentSlot}
          handleSlotClick={handleSlotClick}
        />
        {/* Red side */}
        <DraftSide
          label="Rivals 🌸"
          color="#F2A7C3"
          side="red"
          bans={draft.redBans}
          picks={draft.redPicks}
          isActive={!isDone && currentStep.team === 'red'}
          puffing={puffing}
          isMostRecentSlot={isMostRecentSlot}
          handleSlotClick={handleSlotClick}
        />
      </div>

      {/* Champion picker */}
      {!isDone && (
        <div className="cozy-card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 16 }}>
              {currentStep.action === 'ban' ? '✕ Choose a champion to BAN' : '✓ Choose a champion to PICK'}
            </div>
            <div style={{ flex: 1 }}>
              <input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="🔍 Search..."
                style={{
                  border: '2px solid var(--border-default)', borderRadius: 12, padding: '6px 12px',
                  fontSize: 13, fontFamily: 'Nunito', fontWeight: 700, color: 'var(--text-primary)',
                  background: 'var(--surface-nested)', outline: 'none', width: '100%', boxSizing: 'border-box',
                }}
              />
            </div>
          </div>
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(64px, 1fr))',
            gap: 6, maxHeight: '32vh', overflowY: 'auto',
          }}>
            {champList.map(champ => (
              <div
                key={champ.id}
                onClick={() => handlePick(champ.id)}
                title={champ.name}
                className="champion-sticker"
                style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, cursor: 'pointer' }}
              >
                <window.ChampionIcon championId={champ.id} size={52} noAnim />
                <span style={{ fontSize: 9, fontWeight: 700, color: 'var(--text-primary)', textAlign: 'center',
                  maxWidth: 62, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {champ.name}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ─── Saved scenarios ─── */}
      <SavedScenariosPanel
        scenarios={scenarios}
        champions={champions}
        expanded={expanded}
        setExpanded={setExpanded}
        onLoad={loadScenario}
        onDelete={deleteScenario}
        onRename={renameScenario}
        onAddNote={addNote}
        onEditNote={editNote}
        onDeleteNote={deleteNote}
      />

      {/* ─── Save-scenario prompt ─── */}
      {showSavePrompt && (
        <SaveScenarioPrompt
          name={nameDraft}
          setName={setNameDraft}
          onCancel={() => setShowSavePrompt(false)}
          onSave={commitSave}
          summary={draft}
          champions={champions}
        />
      )}

      {/* ─── Confirm rollback modal ─── */}
      {confirmUndoData && (
        <div
          onMouseDown={e => { if (e.target === e.currentTarget) setConfirmUndoData(null); }}
          style={{
            position: 'fixed', inset: 0, zIndex: 1000,
            background: 'rgba(74, 55, 40, 0.5)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 16,
          }}
        >
          <div className="cozy-card pop-in" style={{
            width: '100%', maxWidth: 420, padding: 22,
            display: 'flex', flexDirection: 'column', gap: 14,
            textAlign: 'center'
          }}>
            <div className="corner-dot corner-dot-bl"></div>
            <div className="corner-dot corner-dot-br"></div>

            <div style={{ marginTop: 4 }}>
              <h2 className="fredoka" style={{ color: '#E85555', fontSize: 22, margin: 0 }}>
                Undo back to here?
              </h2>
              <p style={{ color: 'var(--text-primary)', fontWeight: 700, fontSize: 14, marginTop: 10, lineHeight: 1.5 }}>
                This will remove all picks and bans after <strong>{confirmUndoData.championName}</strong> too.
              </p>
            </div>

            <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 8 }}>
              <window.CozyButton color="cream" onClick={() => setConfirmUndoData(null)}>
                Cancel 👋
              </window.CozyButton>
              <window.CozyButton color="red" onClick={() => {
                undoToStep(confirmUndoData.targetStepIndex);
                setConfirmUndoData(null);
              }}>
                Yes, roll back ↺
              </window.CozyButton>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function DraftSide({ label, color, side, bans, picks, isActive, puffing, isMostRecentSlot, handleSlotClick }) {
  const resolvedSide = side || (label.includes('🌿') ? 'blue' : 'red');
  return (
    <div className="cozy-card" style={{
      padding: 16, border: isActive ? `2.5px solid ${color}` : '2.5px solid var(--border-emphasis)',
      boxShadow: isActive ? `0 0 0 3px ${color}40, 4px 4px 0 ${color}30` : '4px 4px 0 var(--border-default)',
      transition: 'all 0.3s',
    }}>
      <div className="fredoka" style={{ color, fontSize: 18, marginBottom: 12, textAlign: 'center' }}>
        {label}
      </div>

      {/* Bans */}
      <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-muted)', marginBottom: 6, letterSpacing: 1 }}>BANS</div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
        {bans.map((b, i) => {
          const isPuffing = puffing && puffing.side === resolvedSide && puffing.action === 'ban' && puffing.slot === i;
          const isLast = isMostRecentSlot(resolvedSide, 'ban', i);
          const showChamp = b || isPuffing;
          const champId = b || puffing?.championId;

          return (
            <div
              key={i}
              className={isLast ? 'ft-glow-active' : ''}
              style={{
                position: 'relative',
                width: 36,
                height: 36,
                borderRadius: 8,
                overflow: isPuffing ? 'visible' : 'hidden',
              }}
            >
              {showChamp ? (
                <div style={{ position: 'relative', width: '100%', height: '100%' }}>
                  <window.ChampionIcon
                    championId={champId}
                    size={36}
                    noAnim
                    className={isPuffing ? 'cozy-puff-anim' : ''}
                    style={{ borderRadius: 8 }}
                  />
                  {!isPuffing && (
                    <div style={{
                      position: 'absolute', inset: 0, background: 'rgba(74, 55, 40, 0.5)',
                      borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 16, color: '#fff', pointerEvents: 'none',
                    }}>✕</div>
                  )}
                  {!isPuffing && b && (
                    <div
                      className="ft-undo-overlay"
                      onClick={() => handleSlotClick(resolvedSide, 'ban', i, b)}
                    >
                      <span style={{ fontSize: 16, color: '#FFF5E6' }}>↺</span>
                    </div>
                  )}
                </div>
              ) : (
                <div style={{
                  width: 36, height: 36, borderRadius: 8,
                  border: '1.5px dashed var(--border-default)', background: 'var(--surface-nested)',
                }} />
              )}
            </div>
          );
        })}
      </div>

      {/* Picks */}
      <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-muted)', marginBottom: 6, letterSpacing: 1 }}>PICKS</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {picks.map((p, i) => {
          const pickNum = i + 1;
          const pickLabel = resolvedSide === 'blue' ? `Blue Pick ${pickNum} (B${pickNum})` : `Red Pick ${pickNum} (R${pickNum})`;

          const isPuffing = puffing && puffing.side === resolvedSide && puffing.action === 'pick' && puffing.slot === i;
          const isLast = isMostRecentSlot(resolvedSide, 'pick', i);
          const showChamp = p || isPuffing;
          const champId = p || puffing?.championId;

          return (
            <div key={i} className={isLast ? 'ft-glow-active' : ''} style={{
              display: 'flex', alignItems: 'center', gap: 8,
              background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
              borderRadius: 10, padding: '4px 8px',
              position: 'relative',
              overflow: 'hidden'
            }}>
              <div style={{ position: 'relative', width: 36, height: 36 }}>
                {showChamp ? (
                  <>
                    <window.ChampionIcon
                      championId={champId}
                      size={36}
                      noAnim
                      className={isPuffing ? 'cozy-puff-anim' : ''}
                      style={{ borderRadius: 8 }}
                    />
                    {!isPuffing && p && (
                      <div
                        className="ft-undo-overlay"
                        onClick={() => handleSlotClick(resolvedSide, 'pick', i, p)}
                      >
                        <span style={{ fontSize: 16, color: '#FFF5E6' }}>↺</span>
                      </div>
                    )}
                  </>
                ) : (
                  <div style={{
                    width: 36, height: 36, borderRadius: 8,
                    border: '1.5px dashed var(--border-default)', background: 'var(--surface-nested)',
                  }} />
                )}
              </div>
              <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-primary)' }}>
                <span style={{ color: p ? 'var(--text-muted)' : 'var(--text-muted)', marginRight: 6 }}>
                  {pickLabel}:
                </span>
                {p || <span style={{ color: 'var(--text-muted)' }}>Empty slot…</span>}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { DraftSimulator });

// ─────────────────────────────────────────────────────────────────────────────
// Saved scenarios — list, expand, comments thread, load/rename/delete.
// ─────────────────────────────────────────────────────────────────────────────
function ScenarioSummary({ scenario, champions, compact = false }) {
  // Two thin rows (bans + picks per side) so the whole 20-slot draft is visible
  // at a glance on the card.
  const row = (label, ids, color) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
      <span style={{
        fontSize: 9, fontWeight: 800, color, width: 32, flexShrink: 0,
        letterSpacing: 0.5,
      }}>{label}</span>
      <div style={{ display: 'flex', gap: 3, flex: 1, flexWrap: 'wrap' }}>
        {ids.map((id, i) => (
          <div key={i} style={{ position: 'relative' }}>
            {id ? (
              <window.ChampionIcon championId={id} size={compact ? 22 : 26} noAnim />
            ) : (
              <div style={{
                width: compact ? 22 : 26, height: compact ? 22 : 26, borderRadius: 6,
                border: '1.5px dashed var(--border-default)', background: 'var(--surface-card)',
              }} />
            )}
            {id && label.startsWith('BAN') && (
              <div style={{
                position: 'absolute', inset: 0, background: '#4A372870',
                borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 10, color: '#FFFAF3', fontWeight: 800,
              }}>✕</div>
            )}
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="responsive-two-column" style={{
      background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
      borderRadius: 12, padding: '8px 10px',
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ fontFamily: 'Fredoka One', fontSize: 11, color: '#7CBF8E' }}>Our Crew 🌿</div>
        {row('BANS', scenario.blueBans  || [], '#7CBF8E')}
        {row('PICK', scenario.bluePicks || [], '#7CBF8E')}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ fontFamily: 'Fredoka One', fontSize: 11, color: '#F2A7C3' }}>Rivals 🌸</div>
        {row('BANS', scenario.redBans  || [], '#F2A7C3')}
        {row('PICK', scenario.redPicks || [], '#F2A7C3')}
      </div>
    </div>
  );
}

function ScenarioCard({
  scenario, champions, isOpen, onToggle,
  onLoad, onDelete, onRename,
  onAddNote, onEditNote, onDeleteNote,
}) {
  const [renaming, setRenaming] = useState(false);
  const [draft, setDraft] = useState(scenario.name);

  const commitRename = () => {
    const v = draft.trim();
    if (v && v !== scenario.name) onRename(scenario.id, v);
    setRenaming(false);
  };

  const totalNotes = (scenario.notes || []).length;
  const dateLabel = (() => {
    try { return new Date(scenario.savedAt).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }); }
    catch { return scenario.savedAt; }
  })();

  return (
    <div className="cozy-card" style={{ padding: 16, position: 'relative' }}>
      <div className="corner-dot corner-dot-bl"></div>
      <div className="corner-dot corner-dot-br"></div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginTop: 4, marginBottom: 10 }}>
        {renaming ? (
          <input
            autoFocus value={draft} onChange={e => setDraft(e.target.value)}
            onBlur={commitRename}
            onKeyDown={e => { if (e.key === 'Enter') commitRename(); if (e.key === 'Escape') setRenaming(false); }}
            className="fredoka"
            style={{
              flex: 1, minWidth: 200, fontSize: 17, color: 'var(--text-primary)', background: 'transparent',
              border: 'none', borderBottom: '2px solid var(--border-emphasis)', outline: 'none',
              fontFamily: 'Fredoka One, cursive',
            }}
          />
        ) : (
          <span
            className="fredoka"
            onClick={() => { setRenaming(true); setDraft(scenario.name); }}
            style={{ fontSize: 17, color: 'var(--text-primary)', cursor: 'pointer' }}
            title="Click to rename"
          >
            {scenario.name} ✏️
          </span>
        )}
        <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-muted)' }}>
          {dateLabel}
        </span>

        <div style={{ marginLeft: 'auto', display: 'inline-flex', gap: 6 }}>
          <window.CozyButton small color="sage" onClick={() => onLoad(scenario)}>
            🎲 Load
          </window.CozyButton>
          <window.CozyButton
            small
            color={totalNotes > 0 ? 'lavender' : 'cream'}
            onClick={() => onToggle(isOpen ? null : scenario.id)}
          >
            💬 {totalNotes || ''} {isOpen ? 'Hide' : 'Notes'}
          </window.CozyButton>
          <window.CozyButton small color="red" onClick={() => onDelete(scenario.id)}>
            🗑️
          </window.CozyButton>
        </div>
      </div>

      <ScenarioSummary scenario={scenario} champions={champions} />

      {isOpen && (
        <div style={{
          marginTop: 12, paddingTop: 12,
          borderTop: '1.5px dashed var(--border-default)',
        }}>
          <window.CompNotes
            notes={scenario.notes || []}
            onAdd={(note) => onAddNote(scenario.id, note)}
            onEdit={(noteId, text) => onEditNote(scenario.id, noteId, text)}
            onDelete={(noteId) => onDeleteNote(scenario.id, noteId)}
            title="Crew comments"
            emoji="💬"
            compact
            placeholder="Thoughts on this draft? What would you change?"
          />
        </div>
      )}
    </div>
  );
}

function SavedScenariosPanel({
  scenarios, champions, expanded, setExpanded,
  onLoad, onDelete, onRename,
  onAddNote, onEditNote, onDeleteNote,
}) {
  return (
    <div style={{ marginTop: 20 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10 }}>
        <h2 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 20, margin: 0 }}>
          📦 Saved Scenarios
        </h2>
        <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-muted)' }}>
          {scenarios.length} saved
        </span>
      </div>

      {scenarios.length === 0 ? (
        <div className="cozy-card" style={{ padding: 28, textAlign: 'center' }}>
          <div className="corner-dot corner-dot-bl"></div>
          <div className="corner-dot corner-dot-br"></div>
          <div className="float" style={{ display: 'inline-block', marginBottom: 8 }}>
            <window.PawPrint size={22} color="var(--accent-orange)" />
          </div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 18, marginBottom: 4 }}>
            No saved scenarios yet
          </div>
          <div style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 13 }}>
            Draft something, then tap <strong>💾 Save scenario</strong> to share it with the crew 🌱
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {scenarios.map(sc => (
            <ScenarioCard
              key={sc.id}
              scenario={sc}
              champions={champions}
              isOpen={expanded === sc.id}
              onToggle={setExpanded}
              onLoad={onLoad}
              onDelete={onDelete}
              onRename={onRename}
              onAddNote={onAddNote}
              onEditNote={onEditNote}
              onDeleteNote={onDeleteNote}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function SaveScenarioPrompt({ name, setName, onCancel, onSave, summary, champions }) {
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onCancel();
      if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) onSave();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onCancel, onSave]);

  return (
    <div
      onMouseDown={e => { if (e.target === e.currentTarget) onCancel(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(74, 55, 40, 0.5)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
      }}
    >
      <div className="cozy-card pop-in" style={{
        width: '100%', maxWidth: 560, padding: 22,
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <div className="corner-dot corner-dot-bl"></div>
        <div className="corner-dot corner-dot-br"></div>

        <div style={{ marginTop: 4 }}>
          <h2 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 22, margin: 0 }}>
            💾 Save this scenario
          </h2>
          <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 13, margin: '4px 0 0' }}>
            Give it a memorable name so the crew can find it later.
          </p>
        </div>

        <input
          autoFocus
          value={name}
          onChange={e => setName(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') onSave(); }}
          placeholder="e.g. Bo3 vs Noxus — Game 2 sidelane comp"
          style={{
            width: '100%', boxSizing: 'border-box',
            padding: '10px 14px',
            border: '2px solid var(--border-emphasis)', borderRadius: 999,
            fontFamily: 'Nunito', fontSize: 14, fontWeight: 800,
            color: 'var(--text-primary)', background: 'var(--surface-nested)', outline: 'none',
          }}
        />

        <ScenarioSummary scenario={summary} champions={champions} />

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <window.CozyButton color="cream" onClick={onCancel}>Cancel 👋</window.CozyButton>
          <window.CozyButton color="sage" onClick={onSave}>Save 🌟</window.CozyButton>
        </div>
      </div>
    </div>
  );
}
