// STAR story vault

const SEED_STORIES = [
  { id: 'copilot_ctx',   theme: 'Trade-off / scope cut',         seed: 'copilot-ctx: framing decision to cut scope but ship the artifact senior leadership reviewed.' },
  { id: 'ml_debug',      theme: 'Hardest production bug',        seed: 'ML production debug — root cause + how you found it.' },
  { id: 'stakeholder',   theme: 'Disagreement with stakeholder', seed: 'A time you pushed back on a product/manager ask and the outcome.' },
  { id: 'mle_to_sde',    theme: 'Why MLE → SDE switch',          seed: 'Frame as: infra + ML background → systems perspective most SDEs lack.' },
  { id: 'tight_deadline',theme: 'Working under tight deadline',  seed: '' },
  { id: 'mentor',        theme: 'Mentoring / influence',         seed: '' },
  { id: 'failure',       theme: 'A failure & what you learned',  seed: '' },
  { id: 'cross_team',    theme: 'Cross-team collaboration',      seed: '' },
];

function StoriesView() {
  const { state, update } = useStore();

  // Hydrate seeds once
  React.useEffect(() => {
    const missing = SEED_STORIES.filter(s => !state.stories[s.id]);
    if (missing.length === 0) return;
    update(prev => {
      const next = { ...prev.stories };
      for (const s of missing) {
        if (!next[s.id]) next[s.id] = { id: s.id, theme: s.theme, situation: s.seed, task: '', action: '', result: '', rehearsals: 0 };
      }
      return { ...prev, stories: next };
    });
  }, []);

  const setStory = (id, patch) => {
    update(prev => ({ ...prev, stories: { ...prev.stories, [id]: { ...prev.stories[id], ...patch } } }));
  };
  const addCustom = () => {
    const id = `s_${Date.now()}`;
    setStory(id, { id, theme: 'New story', situation: '', task: '', action: '', result: '', rehearsals: 0 });
  };
  const removeStory = (id) => {
    update(prev => {
      const next = { ...prev.stories };
      delete next[id];
      return { ...prev, stories: next };
    });
  };

  const stories = Object.values(state.stories || {});
  const ready = stories.filter(s => s.situation && s.task && s.action && s.result).length;
  const totalRehearsals = stories.reduce((a, s) => a + (s.rehearsals || 0), 0);

  return (
    <div className="fade-in">
      <div className="section-h">
        <div>
          <div className="kicker">Behavioral · 90-second targets</div>
          <h1 className="h-title">STAR <em>vault</em>.</h1>
        </div>
        <div style={{display:'flex',gap:'14px'}}>
          <Stat label="Drafted" value={<CountUp to={ready} />} sub={`of ${stories.length}`} accent />
          <Stat label="Rehearsals" value={<CountUp to={totalRehearsals} />} sub="say out loud" />
        </div>
      </div>

      <div style={{marginBottom:'18px', display:'flex', justifyContent:'flex-end'}}>
        <button className="btn" onClick={addCustom}>+ New story</button>
      </div>

      <div className="col" style={{gap:'14px'}}>
        {stories.map((s, i) => (
          <div key={s.id} className="card" style={{
            animation: `fadeUp 0.3s ${i*30}ms cubic-bezier(0.2,0.8,0.2,1) both`,
            borderColor: (s.situation && s.task && s.action && s.result) ? 'var(--accent)' : 'var(--line-soft)',
          }}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'12px',gap:'12px'}}>
              <input className="input"
                value={s.theme || ''}
                onChange={e => setStory(s.id, { theme: e.target.value })}
                style={{fontSize:'15px', fontWeight:600, background:'transparent', border:'none', padding:'4px 0'}}/>
              <div style={{display:'flex',alignItems:'center',gap:'10px'}}>
                <span className="mono muted" style={{fontSize:'10px'}}>REHEARSED</span>
                <button className="btn" onClick={() => setStory(s.id, { rehearsals: (s.rehearsals||0) + 1 })}
                  style={{padding:'4px 10px',fontSize:'11px'}}>×{s.rehearsals || 0} +</button>
                <button className="btn ghost" onClick={() => removeStory(s.id)} style={{color:'var(--rose)',fontSize:'11px'}}>×</button>
              </div>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:'12px'}}>
              {['situation','task','action','result'].map(k => (
                <div key={k}>
                  <div className="mono" style={{fontSize:'10px',letterSpacing:'0.14em',color:'var(--ink-3)',marginBottom:'6px'}}>{k.toUpperCase()}</div>
                  <textarea
                    className="textarea"
                    placeholder={k}
                    value={s[k] || ''}
                    onChange={e => setStory(s.id, { [k]: e.target.value })}
                    style={{minHeight:'60px',fontSize:'12px'}}
                  />
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.StoriesView = StoriesView;
