
// SavedDrafts.jsx — Recipe Box with Win Condition Tags (Feature 9)
const { useState, useRef, useEffect } = React;
const { useApp } = window;

const WIN_CON_TAGS = [
  { id: 'teamfight',   label: 'Teamfight 💪',        color: '#C5B4E3', border: '#9e87cc' },
  { id: 'pick',        label: 'Pick/Assassinate 🗡️', color: '#F9D0D0', border: '#E8A0A0' },
  { id: 'splitpush',   label: 'Split Push 🌿',        color: '#B8E0C0', border: '#7CBF8E' },
  { id: 'poke',        label: 'Poke & Siege ✨',       color: '#F7DFA0', border: '#c8ae65' },
  { id: 'protect',     label: 'Protect the Carry 💖', color: '#F2A7C3', border: '#c97da0' },
  { id: 'engage',      label: 'Hard Engage ⚡',        color: '#AED6F1', border: '#5b9abf' },
  { id: 'skirmish',    label: 'Skirmish & Peel 🌀',   color: '#F7DFA0', border: '#c8ae65' },
];

function deriveWinConTag(vibe) {
  if (!vibe) return null;
  if (vibe.includes('Teamfight'))  return 'teamfight';
  if (vibe.includes('Pick'))       return 'pick';
  if (vibe.includes('Split'))      return 'splitpush';
  if (vibe.includes('Poke'))       return 'poke';
  if (vibe.includes('Protect'))    return 'protect';
  if (vibe.includes('Engage'))     return 'engage';
  return null;
}

function WinConTag({ tagId, size = 'normal' }) {
  const tag = WIN_CON_TAGS.find(t => t.id === tagId);
  if (!tag) return null;
  return (
    <span style={{
      background: tag.color + '80', border: `1.5px solid ${tag.border}`,
      borderRadius: 20, padding: size === 'small' ? '2px 8px' : '4px 12px',
      fontSize: size === 'small' ? 10 : 12, fontWeight: 800,
      color: 'var(--text-on-light-pastel)', fontFamily: 'Nunito',
      display: 'inline-flex', alignItems: 'center', gap: 4,
    }}>{tag.label}</span>
  );
}

function SavedCardRoleSlot({ pos, slot, champions, onSwap }) {
  const [showPopup, setShowPopup] = useState(false);
  const timerRef = useRef(null);

  const slotData = window.normalizeRoleSlot ? window.normalizeRoleSlot(slot) : { championId: slot || null, alternates: [] };
  const primaryId = slotData.championId;
  const alternates = slotData.alternates;
  const hasAlternates = alternates.length > 0;

  useEffect(() => {
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, []);

  const handleMouseEnter = () => {
    if (!hasAlternates) return;
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      setShowPopup(true);
    }, 350);
  };

  const handleMouseLeave = () => {
    if (timerRef.current) clearTimeout(timerRef.current);
    setShowPopup(false);
  };

  const handleClick = (e) => {
    if (!hasAlternates) return;
    e.stopPropagation();
    setShowPopup(prev => !prev);
  };

  return (
    <div
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      onClick={handleClick}
      style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
        position: 'relative', cursor: hasAlternates ? 'pointer' : 'default',
      }}
    >
      <div style={{ position: 'relative' }}>
        <window.ChampionIcon championId={primaryId} size={44} noAnim />
        {hasAlternates && (
          <div style={{
            position: 'absolute', bottom: -2, right: -2,
            background: 'var(--accent-orange)', color: 'white',
            borderRadius: 8, padding: '0 4px', fontSize: 9, fontWeight: 900,
            lineHeight: '13px', boxShadow: '0 1px 3px rgba(0,0,0,0.35)',
            pointerEvents: 'none', border: '1px solid var(--surface-card)',
          }}>
            +{alternates.length}
          </div>
        )}
      </div>
      <span style={{ fontSize: 9, color: 'var(--text-muted)', fontWeight: 700 }}>{pos.slice(0, 3)}</span>

      {/* Alternates swap popover */}
      {showPopup && hasAlternates && (
        <div
          onClick={(e) => e.stopPropagation()}
          onMouseEnter={() => { if (timerRef.current) clearTimeout(timerRef.current); }}
          style={{
            position: 'absolute', bottom: '100%', left: '50%', transform: 'translateX(-50%)',
            marginBottom: 6, background: 'var(--surface-modal)',
            border: '2px solid var(--border-emphasis)', borderRadius: 14,
            padding: '6px 8px', display: 'flex', gap: 6, alignItems: 'center',
            boxShadow: '0 8px 24px rgba(0,0,0,0.3)', zIndex: 70,
            whiteSpace: 'nowrap',
          }}
        >
          {alternates.map(altId => (
            <div
              key={altId}
              onClick={(e) => {
                e.stopPropagation();
                onSwap(pos, altId);
                setShowPopup(false);
              }}
              title={`Swap to ${champions[altId]?.name || altId}`}
              className="champion-sticker"
              style={{
                cursor: 'pointer', display: 'flex', flexDirection: 'column',
                alignItems: 'center', gap: 2,
              }}
            >
              <window.ChampionIcon championId={altId} size={30} noAnim style={{ borderRadius: '50%' }} />
              <span style={{
                fontSize: 8, fontWeight: 800, color: 'var(--text-primary)',
                maxWidth: 36, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              }}>
                {champions[altId]?.name ? champions[altId].name.slice(0, 5) : altId.slice(0, 5)}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function SavedCompCard({
  comp,
  champions,
  analyzeComp,
  getRating,
  setRating,
  getWinCon,
  customWinCons,
  setCustomWinCons,
  expandedNotes,
  setExpandedNotes,
  handleLoad,
  handleDelete,
  addSavedCompNote,
  addNoteToComp,
  editSavedCompNote,
  deleteSavedCompNote,
  renameComp,
  updateSavedCompRole,
  POSITIONS,
}) {
  const [editing, setEditing] = useState(false);
  const debouncedName = window.useDebounceFirebaseUpdate(
    comp.name || 'Unnamed Recipe',
    (val) => renameComp(comp.id, val)
  );

  const rating = getRating(comp.id);
  const analysis = analyzeComp(champions, comp);
  const winConId = getWinCon(comp, analysis);

  const cleanToArray = (val) => {
    if (window.firebaseToArray) return window.firebaseToArray(val);
    if (!val) return [];
    if (Array.isArray(val)) return val.filter(Boolean);
    if (typeof val === 'object') return Object.values(val).filter(Boolean);
    return [];
  };
  const compNotes = cleanToArray(comp.notes);
  const handleSwapAlternate = (pos, altId) => {
    const newRoleData = window.promoteAlternateToStarter
      ? window.promoteAlternateToStarter(comp[pos], altId)
      : { championId: altId, alternates: [] };

    if (updateSavedCompRole) {
      updateSavedCompRole(comp.id, pos, newRoleData);
    }
  };

  return (
    <div className="cozy-card" style={{ padding: 18, display: 'flex', flexDirection: 'column', height: '100%', boxSizing: 'border-box' }}>
      {/* Name row */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        {editing ? (
          <input
            value={debouncedName.value}
            onChange={e => debouncedName.onChange(e.target.value)}
            onBlur={() => {
              debouncedName.onBlur();
              setEditing(false);
            }}
            onFocus={debouncedName.onFocus}
            onKeyDown={e => {
              if (e.key === 'Enter') {
                debouncedName.onBlur();
                setEditing(false);
              }
            }}
            autoFocus
            className="fredoka"
            style={{
              flex: 1, fontSize: 18, color: 'var(--text-primary)', background: 'transparent',
              border: 'none', borderBottom: '2px solid var(--border-emphasis)', outline: 'none',
              fontFamily: 'Fredoka One, cursive',
            }}
          />
        ) : (
          <span
            className="fredoka"
            onClick={() => { setEditing(true); }}
            style={{ flex: 1, fontSize: 18, color: 'var(--text-primary)', cursor: 'pointer' }}
            title="Click to rename"
          >
            {comp.name || 'Unnamed Recipe'} ✏️
          </span>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
          <span style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 700 }}>
            {comp.savedAt}
          </span>
          {comp.savedByName && (
            <span style={{
              fontSize: 10,
              color: '#7CBF8E',
              fontWeight: 800,
              background: '#B8E0C030',
              padding: '1.5px 6px',
              borderRadius: 8,
              marginTop: 2,
              display: 'inline-flex',
              alignItems: 'center',
              gap: 3,
              border: '1.5px solid #7CBF8E30',
              whiteSpace: 'nowrap'
            }}>
              Saved by {comp.savedByName} 🐾
            </span>
          )}
        </div>
      </div>

      {/* Champion stickers */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
        {POSITIONS.map(pos => (
          <SavedCardRoleSlot
            key={pos}
            pos={pos}
            slot={comp[pos]}
            champions={champions}
            onSwap={handleSwapAlternate}
          />
        ))}
      </div>

      {/* Vibe + Win Condition tags */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 10 }}>
        {analysis && (
          <span style={{
            background: 'var(--surface-nested)', border: '1.5px solid var(--border-default)',
            borderRadius: 12, padding: '4px 10px',
            fontSize: 12, fontWeight: 800, color: 'var(--accent-orange)',
          }}>
            {analysis.vibe}
          </span>
        )}
        {winConId && <WinConTag tagId={winConId} />}
      </div>

      {/* Win-con override picker */}
      <div style={{ marginBottom: 12, minHeight: 60 }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-muted)', marginBottom: 6 }}>
          WIN CONDITION TAG
        </div>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {WIN_CON_TAGS.map(tag => (
            <button
              key={tag.id}
              onClick={() => setCustomWinCons(prev => ({
                ...prev,
                [comp.id]: prev[comp.id] === tag.id ? null : tag.id,
              }))}
              className="cozy-btn"
              style={{
                padding: '2px 8px', fontSize: 10, fontWeight: 800,
                border: `1.5px solid ${customWinCons[comp.id] === tag.id ? tag.border : 'var(--border-default)'}`,
                borderRadius: 10, fontFamily: 'Nunito', cursor: 'pointer',
                background: customWinCons[comp.id] === tag.id ? tag.color : 'transparent',
                color: customWinCons[comp.id] === tag.id ? 'var(--text-on-light-pastel)' : 'var(--text-primary)',
              }}
            >{tag.label}</button>
          ))}
        </div>
      </div>

      {/* Star rating */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 14 }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-primary)' }}>Your rating:</span>
        {[1, 2, 3, 4, 5].map(s => (
          <span
            key={s}
            onClick={() => setRating(comp.id, s)}
            style={{
              fontSize: 18, cursor: 'pointer',
              color: s <= rating ? '#F7DFA0' : 'var(--border-default)',
              textShadow: s <= rating ? '0 0 4px rgba(196, 132, 90, 0.6)' : 'none',
              transition: 'all 0.15s',
            }}
          >★</span>
        ))}
      </div>

      {/* Actions */}
      <div style={{ display: 'flex', gap: 8, marginTop: 'auto' }}>
        <window.CozyButton small color="sage" onClick={() => handleLoad(comp)}>
          🍲 Load Comp
        </window.CozyButton>
        <window.CozyButton small color="red" onClick={() => handleDelete(comp.id)}>
          👋 Delete
        </window.CozyButton>
        <window.CozyButton
          small
          color={compNotes.length > 0 ? 'lavender' : 'cream'}
          onClick={() => setExpandedNotes(prev => ({ ...prev, [comp.id]: !prev[comp.id] }))}
          style={{ marginLeft: 'auto' }}
        >
          💬 {compNotes.length > 0 ? `${compNotes.length} ` : ''}{expandedNotes[comp.id] ? 'Hide' : 'Notes'}
        </window.CozyButton>
      </div>

      {/* Editable crew notes — collapses by default to keep cards compact */}
      {expandedNotes[comp.id] && (
        <div style={{
          marginTop: 12, paddingTop: 12,
          borderTop: '1.5px dashed var(--border-default)',
        }}>
          <window.CompNotes
            notes={compNotes}
            onAdd={(note) => (addNoteToComp || addSavedCompNote)(comp.id, note)}
            onEdit={(noteId, text) => editSavedCompNote(comp.id, noteId, text)}
            onDelete={(noteId) => deleteSavedCompNote(comp.id, noteId)}
            title="Crew notes"
            emoji="💬"
            compact
            placeholder="Anything to add now that you've thought about it?"
          />
        </div>
      )}
    </div>
  );
}

function SavedDrafts() {
  const {
    savedComps, deleteComp, setActiveComp, setActiveCompNotes,
    setTab, champions, analyzeComp, showToast, POSITIONS,
    addSavedCompNote, addNoteToComp, editSavedCompNote, deleteSavedCompNote,
    renameComp, updateSavedCompRole,
  } = useApp();
  const [editingId, setEditingId] = useState(null);
  const [editName, setEditName] = useState('');
  const [ratings, setRatings] = useState({});
  const [customWinCons, setCustomWinCons] = useState({}); // override per comp id
  const [filterTag, setFilterTag] = useState('all');
  const [expandedNotes, setExpandedNotes] = useState({});

  const handleDelete = (id) => {
    deleteComp(id);
    showToast('Bye bye! 👋');
  };

  const handleLoad = (comp) => {
    const picked = {};
    POSITIONS.forEach(p => {
      picked[p] = window.normalizeRoleSlot ? window.normalizeRoleSlot(comp[p]) : (comp[p] || null);
    });
    setActiveComp(picked);
    const cleanToArray = window.firebaseToArray || ((val) => Array.isArray(val) ? val : []);
    setActiveCompNotes(cleanToArray(comp.notes));
    showToast('Comp loaded! 🍲');
    setTab('comp');
  };

  const getRating = (id) => ratings[id] || 0;
  const setRating = (id, r) => setRatings(prev => ({ ...prev, [id]: r }));

  const getWinCon = (comp, analysis) => {
    return customWinCons[comp.id] || deriveWinConTag(analysis?.vibe) || null;
  };

  const filteredComps = filterTag === 'all'
    ? savedComps
    : savedComps.filter(comp => {
        const analysis = analyzeComp(champions, comp);
        return getWinCon(comp, analysis) === filterTag;
      });

  return (
    <div style={{ padding: 20 }}>
      <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, marginBottom: 4 }}>
        Recipe Box 📦
      </h1>
      <p style={{ color: 'var(--text-muted)', fontWeight: 700, fontSize: 14, margin: '0 0 16px 0' }}>
        {savedComps.length} saved comp{savedComps.length !== 1 ? 's' : ''} — your favourite recipes!
      </p>

      {/* Win-con filter row */}
      {savedComps.length > 0 && (
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 20 }}>
          <button
            onClick={() => setFilterTag('all')}
            className="cozy-btn"
            style={{
              padding: '4px 14px', border: `2px solid ${filterTag === 'all' ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
              borderRadius: 20, fontFamily: 'Nunito', fontSize: 12, fontWeight: 800,
              background: filterTag === 'all' ? 'var(--accent-orange)' : 'var(--surface-nested)',
              color: filterTag === 'all' ? 'var(--surface-page)' : 'var(--text-primary)', cursor: 'pointer',
            }}>All</button>
          {WIN_CON_TAGS.map(tag => (
            <button
              key={tag.id}
              onClick={() => setFilterTag(filterTag === tag.id ? 'all' : tag.id)}
              className="cozy-btn"
              style={{
                padding: '4px 12px',
                border: `2px solid ${filterTag === tag.id ? tag.border : 'var(--border-default)'}`,
                borderRadius: 20, fontFamily: 'Nunito', fontSize: 12, fontWeight: 800,
                background: filterTag === tag.id ? tag.color : 'var(--surface-nested)',
                color: filterTag === tag.id ? 'var(--text-on-light-pastel)' : 'var(--text-primary)', cursor: 'pointer',
              }}>{tag.label}</button>
          ))}
        </div>
      )}

      {savedComps.length === 0 ? (
        <div className="cozy-card" style={{ padding: 60, textAlign: 'center' }}>
          <div style={{ fontSize: 52, marginBottom: 12 }}>📦</div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 24, marginBottom: 8 }}>
            Empty recipe box!
          </div>
          <div style={{ color: 'var(--text-muted)', fontWeight: 700, marginBottom: 20 }}>
            Save a comp from the Team Comp tab 🍲 to fill it up!
          </div>
          <window.CozyButton color="sage" onClick={() => setTab('comp')}>
            Start cooking 🍳
          </window.CozyButton>
        </div>
      ) : filteredComps.length === 0 ? (
        <div className="cozy-card" style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ fontSize: 40, marginBottom: 8 }}>🔍</div>
          <div className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 20 }}>No comps with this win condition</div>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
          {filteredComps.map(comp => (
            <SavedCompCard
              key={comp.id}
              comp={comp}
              champions={champions}
              analyzeComp={analyzeComp}
              getRating={getRating}
              setRating={setRating}
              getWinCon={getWinCon}
              customWinCons={customWinCons}
              setCustomWinCons={setCustomWinCons}
              expandedNotes={expandedNotes}
              setExpandedNotes={setExpandedNotes}
              handleLoad={handleLoad}
              handleDelete={handleDelete}
              addSavedCompNote={addSavedCompNote}
              addNoteToComp={addNoteToComp}
              editSavedCompNote={editSavedCompNote}
              deleteSavedCompNote={deleteSavedCompNote}
              renameComp={renameComp}
              updateSavedCompRole={updateSavedCompRole}
              POSITIONS={POSITIONS}
            />
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { SavedDrafts, WinConTag, WIN_CON_TAGS });


