// track_detail.jsx — T-02 트랙 상세

const { Icon, Pill, Tag, Avatar, Button, Progress, KPI } = window.RAlly;

const TRACK_STAGES = [
  { num: 'STAGE 01', title: '출발', meta: '제품 정의 · 의도된 용도 · 규정 매핑', icon: 'flag' },
  { num: 'STAGE 02', title: '본격 주행', meta: 'SOP · 위험관리 · 기술문서 작성', icon: 'run' },
  { num: 'STAGE 03', title: '페이스 조절', meta: '설계 검증 · 임상 평가 · 사용성 검증', icon: 'heart' },
  { num: 'STAGE 04', title: '결승선', meta: 'MFDS 신청 패키지 · 제출', icon: 'trophy' },
];
const deriveStages = (overall) => TRACK_STAGES.map((s, i) => {
  const start = i * 25;
  const pct = Math.max(0, Math.min(100, Math.round(((overall || 0) - start) / 25 * 100)));
  const statusKey = (overall || 0) >= start + 25 ? 'done' : ((overall || 0) >= start ? 'current' : 'waiting');
  return { ...s, progress: pct, statusKey,
    status: statusKey === 'done' ? '완주' : (statusKey === 'current' ? ('진행 중 · ' + pct + '%') : '대기') };
});

const TrackDetail = ({ go }) => {
  const [data, setData] = React.useState(null);
  React.useEffect(() => {
    const load = (tid) => fetch('/api/track/' + tid + '/detail').then((r) => r.json()).then(setData).catch(() => {});
    const sel = (typeof window !== 'undefined' && window.__RALLY_TRACK);
    if (sel) { load(sel); return; }
    // 선택 트랙 없으면 실제 생성 트랙(profile 보유·최신) 해석
    fetch('/api/tracks').then((r) => r.json()).then((d) => {
      const ts = d.tracks || [];
      const real = ts.filter((x) => x.profile);
      const pick = (real.length ? real : ts).slice(-1)[0];
      if (pick) { if (typeof window !== 'undefined') window.__RALLY_TRACK = pick.id; load(pick.id); }
    }).catch(() => {});
  }, []);
  const t = (data && data.track) || { name: '트랙 로딩 중…', stage: 'STAGE 01 · 출발', progress: 0, deadline: null, meta: '' };
  const bd = (data && data.breakdown) || [];
  const stages = deriveStages(t.progress);
  const curIdx = Math.min(3, Math.floor((t.progress || 0) / 25));
  return (
  <div className="page">
    {/* Header */}
    <div className="page__head">
      <div>
        <div className="row" style={{ gap: 8, marginBottom: 6 }}>
          <Pill variant="coral">{t.stage}</Pill>
          <Pill variant="navy">디지털의료기기 소프트웨어</Pill>
          <Pill>디지털의료제품법 / IEC 62304 / ISO 14971 / ISO 13485</Pill>
        </div>
        <div className="page__title">{t.name}</div>
        <div className="page__sub">{t.meta || '품목 정보 기준 적용 문서 트랙'}</div>
      </div>
      <div className="row">
        <Button variant="ghost" icon="share">외부 공유</Button>
        <Button variant="soft" icon="dots" />
      </div>
    </div>

    {/* Navy banner with track */}
    <div className="banner" style={{ marginBottom: 20 }}>
      <div className="banner__row">
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--coral)', marginBottom: 8 }}>
            <span className="live-dot-coral" /> CURRENT POSITION
          </div>
          <div className="banner__big">{t.progress}<span style={{ fontSize: 28, fontWeight: 600, marginLeft: 4, color: 'var(--on-navy-2)' }}>%</span></div>
          <div className="banner__small">주행 완료 · 결승선까지 약 {Math.max(0, 4 - curIdx - 1)} STAGE</div>
        </div>
        <div className="banner__right">
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--on-navy-3)', marginBottom: 8 }}>EXPECTED FINISH</div>
          <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.01em' }}>{t.deadline || '미정'}</div>
          <div className="banner__small">MFDS 품목허가 목표</div>
        </div>
      </div>

      {/* Banner track with 5 notches at 0/25/50/75/100 */}
      <div className="banner-track" style={{ marginTop: 36, marginBottom: 30 }}>
        <div className="banner-track__rail">
          <div className="banner-track__fill" style={{ width: t.progress + '%' }} />
        </div>
        <div className="banner-track__notches">
          {[{ label: '출발' }, ...stages.map((s, i) => ({ label: i === 3 ? '결승선' : ('Stage 0' + (i + 1)) }))].map((n, i) => {
            // i=0 출발(항상 done), i=1..4 = stage 1..4
            const overall = t.progress || 0;
            const done = i === 0 ? true : overall >= i * 25;
            const cur = i > 0 && !done && overall >= (i - 1) * 25;
            const cls = done ? ' banner-track__notch--done' : (cur ? ' banner-track__notch--current' : '');
            const lcls = done ? ' banner-track__label--done' : (cur ? ' banner-track__label--current' : '');
            return (
              <div key={i} style={{ position: 'relative' }}>
                <div className={'banner-track__notch' + cls}>
                  {done && <Icon name="check" size={9} style={{ color: 'var(--navy)', position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, margin: 'auto' }} />}
                </div>
                <div className={'banner-track__label' + lcls}>{n.label}{cur ? ' · 현재' : ''}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>

    {/* 규제 라이프사이클 — 능동형 가이드(지금 할 일·규제 일정·변경 관리) */}
    <LifecyclePanel go={go} />

    {/* 4 STAGE cards (실제 진행률 구동) */}
    <div className="stage-grid">
      {stages.map((s, i) => (
        <StageCard
          key={s.num}
          num={s.num}
          title={s.title}
          meta={s.meta}
          status={s.status}
          statusKey={s.statusKey}
          progress={s.progress}
          icon={s.icon}
          onClick={i === curIdx ? (() => go('kanban')) : undefined}
          cta={i === curIdx ? '문서 보기' : undefined}
        />
      ))}
    </div>

    {/* Current stage detail */}
    <div className="card card--pad-lg" style={{ marginTop: 20 }}>
      <div className="between" style={{ marginBottom: 18 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 4 }}>현재 구간</div>
          <div style={{ fontSize: 20, fontWeight: 700, color: 'var(--ink)' }}>{stages[curIdx].num} · {stages[curIdx].title}</div>
        </div>
        <Button variant="primary" iconRight="arrow_right" onClick={() => go('kanban')}>구간 상세 보기</Button>
      </div>

      <div className="grid-3">
        {bd.map((b) => (
          <SubKPI key={b.key} label={b.label} progress={b.pct} done={b.done} total={b.total}
            meta={b.done + '/' + b.total + ' 완주' + (b.coral ? ' · 미완 항목 있음' : '')} coral={b.coral} />
        ))}
      </div>
    </div>

    {/* Sub-track strip: lane visualization of activity */}
    <div className="card card--pad" style={{ marginTop: 20 }}>
      <div className="section-head">
        <div className="section-head__title">트랙 활동 (지난 7일)</div>
        <div className="row" style={{ gap: 12, fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
          <span className="row" style={{ gap: 4 }}>
            <span style={{ width: 8, height: 8, background: 'var(--green)', borderRadius: 2 }} /> 완주
          </span>
          <span className="row" style={{ gap: 4 }}>
            <span style={{ width: 8, height: 8, background: 'var(--coral)', borderRadius: 2 }} /> 진행
          </span>
          <span className="row" style={{ gap: 4 }}>
            <span style={{ width: 8, height: 8, background: 'var(--surface-3)', borderRadius: 2 }} /> 정체
          </span>
        </div>
      </div>
      <ActivityLanes />
    </div>
  </div>
  );
};

// ── 규제 라이프사이클 패널: 지금 할 일 + 규제 일정 + 변경 관리 (능동형) ──
const LEVEL_STYLE = {
  urgent: { color: 'var(--coral)', bg: 'var(--coral-soft, #FBEAE4)', icon: 'alert' },
  todo:   { color: 'var(--navy)', bg: 'var(--surface-2)', icon: 'arrow_right' },
  input:  { color: 'var(--ink-2)', bg: 'var(--surface-2)', icon: 'edit' },
  info:   { color: 'var(--green)', bg: 'var(--green-soft)', icon: 'check' },
};

const LifecyclePanel = ({ go }) => {
  const [tid, setTid] = React.useState(null);
  const [guide, setGuide] = React.useState(null);
  const [cal, setCal] = React.useState(null);
  const [events, setEvents] = React.useState([]);
  const [picked, setPicked] = React.useState({});
  const [assess, setAssess] = React.useState(null);
  const [dates, setDates] = React.useState({ rev_date: '', gmp_cert_date: '', license_date: '' });
  const [cons, setCons] = React.useState(null);

  const loadAll = (id) => {
    fetch('/api/track/' + id + '/guide').then((r) => r.json()).then(setGuide).catch(() => {});
    fetch('/api/track/' + id + '/calendar').then((r) => r.json()).then(setCal).catch(() => {});
  };
  React.useEffect(() => {
    window.RAlly.resolveTrackId().then((id) => {
      if (!id) return;
      setTid(id); loadAll(id);
      // 날짜 디폴트: 제·개정일=작성일(생성일)
      fetch('/api/track/' + id + '/dates/defaults').then((r) => r.json()).then((d) => {
        if (d.ok) setDates((p) => ({ ...p, ...d.defaults }));
      }).catch(() => {});
    });
    fetch('/api/change/events').then((r) => r.json()).then((d) => setEvents(d.events || [])).catch(() => {});
  }, []);

  const postDates = (patch) => {
    if (!tid) return;
    fetch('/api/track/' + tid + '/dates', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(patch) }).then((r) => r.json()).then((d) => {
        setCal(d); setCons(d.consistency || null); loadAll(tid);
      }).catch(() => {});
  };
  const saveDate = () => postDates({ ...dates });
  const applyChoice = (field, value) => {
    setDates((p) => ({ ...p, [field]: value }));
    postDates({ [field]: value });
  };
  const setDate = (k, v) => setDates((p) => ({ ...p, [k]: v }));
  const runAssess = () => {
    const ids = Object.keys(picked).filter((k) => picked[k]);
    if (!tid || !ids.length) { setAssess(null); return; }
    fetch('/api/change/assess', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ event_ids: ids, track_id: tid }) }).then((r) => r.json()).then(setAssess).catch(() => {});
  };

  const nx = guide && guide.next;
  const actions = (nx && nx.actions) || [];

  // action.kind별 실제 화면 라우팅(죽은 CTA → 흐름 배선)
  const dateCardRef = React.useRef(null);
  const routeAction = (a) => {
    const k = a && a.kind;
    if (k === 'inputs') return go && go('fill');
    if (k === 'ready') return go && go('cert');
    if (k === 'calendar' || k === 'calendar_input') {
      if (dateCardRef.current) dateCardRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
      return;
    }
    return go && go('kanban'); // 'docs' 및 기본
  };

  return (
    <div style={{ marginTop: 20 }}>
      {/* 지금 할 일 */}
      <div className="card card--pad" style={{ marginBottom: 16 }}>
        <div className="section-head" style={{ marginBottom: 12 }}>
          <div className="section-head__title"><Icon name="sparkles" size={15} /> 지금 할 일</div>
          {nx && nx.summary && (
            <span className="muted-2" style={{ fontSize: 12 }}>
              진행 {nx.summary.progress}% · 미완 {nx.summary.undone} · 입력 {nx.summary.inputs_remaining}
            </span>
          )}
        </div>
        {actions.length === 0 && <div className="muted" style={{ fontSize: 13 }}>준비 항목을 불러오는 중…</div>}
        <div style={{ display: 'grid', gap: 8 }}>
          {actions.map((a, i) => {
            const s = LEVEL_STYLE[a.level] || LEVEL_STYLE.info;
            return (
              <div key={i} className="row" style={{ gap: 12, padding: '10px 12px', borderRadius: 8,
                background: s.bg, borderLeft: '3px solid ' + s.color }}>
                <span style={{ fontSize: 16 }}>{a.icon}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{a.title}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 1 }}>{a.detail}</div>
                </div>
                {a.cta && <Button variant="soft" size="sm" onClick={() => routeAction(a)}>{a.cta}</Button>}
              </div>
            );
          })}
        </div>
      </div>

      <div className="grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* 규제 일정 + 날짜 정합성 */}
        <div className="card card--pad" ref={dateCardRef}>
          <div className="section-head__title" style={{ marginBottom: 12 }}><Icon name="calendar" size={15} /> 규제 일정 · 날짜</div>
          {cal && cal.events && cal.events.length > 0 && cal.events.map((e, i) => (
            <div key={i} className="row" style={{ gap: 10, marginBottom: 8 }}>
              <Pill variant={e.level === 'urgent' || e.level === 'overdue' ? 'coral' : (e.level === 'soon' ? 'navy' : 'default')}>{e.dday_label}</Pill>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{e.title} · {e.status}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>기한 {e.due_date}</div>
              </div>
            </div>
          ))}
          {/* 날짜 입력(작성일 디폴트, 수정 가능) */}
          <div style={{ display: 'grid', gap: 8, marginTop: 4 }}>
            {[['rev_date', '제·개정일 (작성일 기본)'], ['gmp_cert_date', 'GMP 적합인정일'], ['license_date', '인허가일']].map(([k, label]) => (
              <div key={k} className="row" style={{ gap: 8 }}>
                <span style={{ width: 108, fontSize: 12, color: 'var(--ink-2)' }}>{label}</span>
                <input type="text" value={dates[k] || ''} onChange={(e) => setDate(k, e.target.value)}
                  placeholder="YYYY.MM.DD"
                  style={{ flex: 1, padding: '6px 9px', border: '1px solid var(--line)', borderRadius: 6, fontSize: 12.5 }} />
              </div>
            ))}
            <Button variant="primary" size="sm" onClick={saveDate}>저장 · 정합성 확인</Button>
          </div>
          {/* 정합성 결과 */}
          {cons && (
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
              <div className="row" style={{ gap: 8, marginBottom: cons.ok ? 0 : 8 }}>
                <Icon name={cons.ok ? 'check' : 'alert'} size={15} style={{ color: cons.ok ? 'var(--green)' : 'var(--coral)' }} />
                <span style={{ fontSize: 12.5, fontWeight: 600, color: cons.ok ? 'var(--green)' : 'var(--coral)' }}>{cons.summary}</span>
              </div>
              {(cons.issues || []).map((it, i) => (
                <div key={i} style={{ marginBottom: 10, padding: 10, background: 'var(--surface-2)', borderRadius: 8 }}>
                  <div style={{ fontSize: 12.5, color: 'var(--ink)', marginBottom: 6 }}>{it.message}</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {it.choices.map((ch, j) => (
                      <button key={j} className="btn btn--soft btn--sm" onClick={() => applyChoice(ch.field, ch.value)}>{ch.label}</button>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 변경 관리 */}
        <div className="card card--pad">
          <div className="section-head__title" style={{ marginBottom: 12 }}><Icon name="layers" size={15} /> 변경 관리</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 10 }}>어떤 변경이 생겼나요? 영향 문서와 규제 경로를 알려드립니다.</div>
          <div style={{ display: 'grid', gap: 4, maxHeight: 140, overflowY: 'auto', marginBottom: 10 }}>
            {events.map((ev) => (
              <label key={ev.id} className="row" style={{ gap: 8, fontSize: 12.5, cursor: 'pointer' }}>
                <input type="checkbox" checked={!!picked[ev.id]}
                  onChange={(e) => setPicked((p) => ({ ...p, [ev.id]: e.target.checked }))} />
                <span>{ev.label}</span>
              </label>
            ))}
          </div>
          <Button variant="soft" size="sm" onClick={runAssess}>변경 영향 평가</Button>
          {assess && assess.ok && (
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
              <div className="row" style={{ gap: 8, marginBottom: 8 }}>
                <Pill variant={assess.significant ? 'coral' : 'navy'}>{assess.primary_route || '문서 갱신'}</Pill>
                {assess.significant && <span className="micro micro--coral">중대한 변경</span>}
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>영향 문서 {(assess.impacted_docs || []).length}건:</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 6 }}>
                {(assess.impacted_docs || []).map((d) => (
                  <span key={d.code} className="pill" style={{ fontSize: 11 }}>
                    {d.label} · {d.exists ? '보강' : '생성'}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const StageCard = ({ num, title, meta, status, statusKey, progress, icon, onClick, cta }) => (
  <div
    className={'stage-card stage-card--' + statusKey}
    onClick={statusKey === 'current' ? onClick : null}
    style={statusKey === 'current' ? { cursor: 'pointer' } : null}
  >
    <div className="between">
      <div className={'stage-card__num' + (statusKey === 'current' ? ' stage-card__num--current' : '')}>
        <Icon name={icon} size={14} />
        {num}
      </div>
      {statusKey === 'done' && (
        <div style={{ width: 22, height: 22, borderRadius: 999, background: 'var(--green-soft)', color: 'var(--green)', display: 'grid', placeItems: 'center' }}>
          <Icon name="check" size={13} />
        </div>
      )}
    </div>
    <div>
      <div className="stage-card__title">{title}</div>
      <div className="stage-card__meta" style={{ marginTop: 4 }}>{meta}</div>
    </div>
    <div className="stage-card__progress">
      <div className={'stage-card__status stage-card__status--' + statusKey} style={{ marginBottom: 6 }}>{status}</div>
      <Progress value={progress} size="sm" />
      {cta && (
        <div style={{ fontSize: 12, color: 'var(--coral)', fontWeight: 600, marginTop: 10 }}>{cta} →</div>
      )}
    </div>
  </div>
);

const SubKPI = ({ label, progress, done, total, meta, coral }) => (
  <div style={{
    border: '1px solid var(--line)',
    borderRadius: 10,
    padding: 18,
    background: 'var(--surface-2)',
  }}>
    <div className="between" style={{ marginBottom: 10 }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--ink-2)' }}>{label}</div>
      <div className="tabular" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{done}/{total}</div>
    </div>
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 10 }}>
      <div className={'tabular'} style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em', color: coral ? 'var(--coral)' : 'var(--ink)', lineHeight: 1 }}>{progress}%</div>
    </div>
    <Progress value={progress} size="sm" />
    <div style={{ fontSize: 12, color: coral ? 'var(--coral-2)' : 'var(--ink-2)', marginTop: 10, fontWeight: coral ? 600 : 400 }}>
      {meta}
    </div>
  </div>
);

// Simple GitHub-style activity lanes — 3 rows × 14 cells
const ActivityLanes = () => {
  const rows = [
    { label: 'SOP',     cells: [1,1,2,1,2,3,1,2,3,3,2,1,2,3] },
    { label: '위험관리', cells: [0,1,1,2,1,0,0,1,2,2,3,2,2,2] },
    { label: '기술문서', cells: [0,0,1,1,1,2,1,1,2,3,2,1,3,3] },
  ];
  // 0 idle (line), 1 idle-light, 2 progress (coral), 3 done (green)
  const colors = ['var(--surface-3)', '#E8E2D6', 'var(--coral)', 'var(--green)'];
  const days = ['5/6','5/7','5/8','5/9','5/10','5/11','5/12','5/13','5/14','5/15','5/16','5/17','5/18','오늘'];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '90px repeat(14, 1fr)', gap: 4, alignItems: 'center', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.05em' }}>
        <div />
        {days.map((d, i) => (
          <div key={i} style={{ textAlign: 'center', fontWeight: i === days.length - 1 ? 700 : 400, color: i === days.length - 1 ? 'var(--coral)' : 'var(--ink-3)' }}>{d}</div>
        ))}
      </div>
      {rows.map((row) => (
        <div key={row.label} style={{ display: 'grid', gridTemplateColumns: '90px repeat(14, 1fr)', gap: 4, alignItems: 'center' }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)' }}>{row.label}</div>
          {row.cells.map((v, i) => (
            <div key={i} style={{
              height: 22,
              borderRadius: 3,
              background: colors[v],
              opacity: v === 0 ? 0.6 : 1,
            }} />
          ))}
        </div>
      ))}
    </div>
  );
};

window.RAlly.TrackDetail = TrackDetail;
