// Execution Roadmap — prioritised backlog.

const { useState: useStateR, useMemo: useMemoR } = React;

const PHASE_LABEL = { P0: 'Phase 1', P1: 'Phase 2', P2: 'Phase 3' };

function RoadmapView() {
  const all = window.ROADMAP;
  const next = window.RECOMMENDED_NEXT;
  const [filter, setFilter] = useStateR('All');
  const [expanded, setExpanded] = useStateR(new Set(['r1']));
  const [legendOpen, setLegendOpen] = useStateR(false);

  const deferred = useMemoR(() => {
    const roadmapIds = new Set(all.map(r => r.workflowRef).filter(Boolean));
    return (window.WORKFLOWS || [])
      .map(w => ({ ...w, readiness: window.computeReadiness(w) }))
      .filter(w => !roadmapIds.has(w.id) && w.status !== 'Already handled');
  }, [all]);

  const filters = ['All', 'P0', 'P1', 'P2', ...(deferred.length > 0 ? ['Deferred'] : [])];
  const items = useMemoR(() =>
    filter === 'All' || filter === 'Deferred' ? all : all.filter(i => i.priority === filter),
  [all, filter]);
  const showDeferred = filter === 'All' || filter === 'Deferred';

  const toggle = (id) => setExpanded(s => {
    const n = new Set(s);
    n.has(id) ? n.delete(id) : n.add(id);
    return n;
  });

  const counts = useMemoR(() => ({
    P0: all.filter(i => i.priority === 'P0').length,
    P1: all.filter(i => i.priority === 'P1').length,
    P2: all.filter(i => i.priority === 'P2').length,
  }), [all]);

  const modelDot = (m) => {
    if (m.startsWith('Managed')) return '#2e5dff';
    if (m.startsWith('One-time')) return '#1a8f59';
    return '#b07a18';
  };

  const MODEL_DESC = {
    'One-time build':                    "Linea designs, builds, and hands over the completed workflow. After a handoff session and documentation, the client owns and operates it with no ongoing Linea involvement.",
    'Managed service':                   "Linea builds and continues to operate the workflow on a monthly retainer — monitoring performance, retraining models as data drifts, and handling integration issues.",
    'Team enablement':                   "Linea builds alongside one or two members of the client's team, transferring skills throughout the engagement. The client leaves with a working workflow and the internal capability to build the next one.",
    'One-time build + 90-day managed run': "Linea builds, then operates the workflow for 90 days while real-world data accumulates and the model stabilises. Handed over at day 90 as a tuned, battle-tested system.",
  };

  return (
    <div className="view roadmap-view">
      <div className="page-head">
        <div>
          <div className="kicker">Section IV</div>
          <h1 className="page-title">Execution Roadmap</h1>
          <p className="page-lede">{all.length} recommended workflows across three phases, ordered by Linea's recommendation. Treat this as a working backlog — sequence and effort estimates were sized in the engagement.{deferred.length > 0 ? ` ${deferred.length} additional workflow${deferred.length !== 1 ? 's' : ''} are deferred pending prerequisites.` : ''}</p>
        </div>
        <div className="prio-summary">
          <div><span className="prio prio--p0">Phase 1</span><b>{counts.P0}</b></div>
          <div><span className="prio prio--p1">Phase 2</span><b>{counts.P1}</b></div>
          <div><span className="prio prio--p2">Phase 3</span><b>{counts.P2}</b></div>
          {deferred.length > 0 && <div><span className="prio prio--deferred">Deferred</span><b>{deferred.length}</b></div>}
        </div>
      </div>

      <div className="next-step">
        <div className="next-step-left">
          <div className="kicker kicker--blue">Recommended Next Step</div>
          <h2 className="next-step-title">{next.title}</h2>
          <p className="next-step-body">{next.body}</p>
        </div>
        <div className="next-step-right">
          <div className="next-step-stat">
            <div className="kicker">Expected return</div>
            <div className="serif-num next-step-stat-v">{(next.returnHours || 0).toLocaleString()}</div>
            <div className="next-step-stat-l">{next.returnLabel || 'hours / year recovered'}</div>
          </div>
          <div className="next-step-stat">
            <div className="kicker">Time to first value</div>
            <div className="serif-num next-step-stat-v">{next.timeToValue || 6}<span style={{fontSize:'0.5em', marginLeft:4}}>{next.timeToValueUnit || 'wk'}</span></div>
            <div className="next-step-stat-l">{next.timeToValueLabel || 'first usable draft in advisor hands'}</div>
          </div>
        </div>
      </div>

      <div className="filter-bar filter-bar--tight">
        <div className="filter-group">
          <span className="filter-label">Phase</span>
          {filters.map(f => (
            <button key={f} className={"chip-btn" + (filter === f ? ' is-active' : '')} onClick={() => setFilter(f)}>
              {PHASE_LABEL[f] || f}
            </button>
          ))}
        </div>
        <button className={"model-legend-toggle" + (legendOpen ? ' is-open' : '')} onClick={() => setLegendOpen(v => !v)}>
          <IconBriefcase size={12}/>
          Delivery model
          <IconChevronDown size={11} style={{transition:'transform 0.2s', transform: legendOpen ? 'rotate(180deg)' : 'none'}}/>
        </button>
      </div>

      {legendOpen && (
        <div className="model-legend">
          {Object.entries(MODEL_DESC).map(([name, desc]) => (
            <div key={name} className="model-legend-item">
              <IconBriefcase size={14} style={{color: modelDot(name), flexShrink:0, marginTop:2}}/>
              <div>
                <div className="model-legend-name">{name}</div>
                <div className="model-legend-desc">{desc}</div>
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="backlog">
        {items.map((it, i) => {
          const open = expanded.has(it.id);
          return (
            <article key={it.id} className={"backlog-row" + (open ? ' is-open' : '')}>
              <button className="backlog-main" onClick={() => toggle(it.id)}>
                <div className="bl-idx serif-num">{String(i+1).padStart(2,'0')}</div>
                <PriorityTag p={it.priority}/>
                <div className="bl-title">{it.title}</div>
                <div className="bl-rationale">{it.rationale}</div>
                <div className="bl-effort"><IconClock size={12}/>{it.effort}</div>
                <div className="bl-model"><IconBriefcase size={12} style={{color: modelDot(it.model), flexShrink:0}}/>{it.model}</div>
                <div className="bl-chev">{open ? <IconChevronUp size={14}/> : <IconChevronDown size={14}/>}</div>
              </button>
              {open && (
                <div className="backlog-detail">
                  <div className="bld-grid">
                    <div className="bld-item">
                      <div className="kicker">Department</div>
                      <div className="bld-v">{it.department}</div>
                    </div>
                    <div className="bld-item">
                      <div className="kicker">Expected impact</div>
                      <div className="bld-v">{it.impact}</div>
                    </div>
                  </div>
                </div>
              )}
            </article>
          );
        })}
        {showDeferred && deferred.length > 0 && deferred.map(w => (
          <article key={w.id} className="backlog-row backlog-row--deferred">
            <div className="backlog-main">
              <div className="bl-idx" />
              <PriorityTag p="Deferred"/>
              <div className="bl-title">{w.name}</div>
              <div className="bl-rationale">{w.impact}</div>
              <div className="bl-effort" />
              <div className="bl-model" />
              <div />
            </div>
          </article>
        ))}
      </div>

      <div className="continue">
        <div className="continue-left">
          <div className="kicker">Where to go next</div>
          <h3 className="continue-h">Take this roadmap forward.</h3>
          <p className="continue-p">This deliverable is yours. The findings, the data audit, and the workflow inventory live here for your team. When you're ready to execute against this roadmap, we're here.</p>
        </div>
        <div className="continue-right">
          <button className="btn-primary">{next.ctaPrimary}<IconArrowUpRight size={14}/></button>
          <button className="btn-ghost">{next.ctaSecondary}</button>
        </div>
      </div>
    </div>
  );
}

window.RoadmapView = RoadmapView;
