// cert.jsx — C-01 인증 패키지 빌더

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

const CertPackage = ({ go }) => {
  const [tab, setTab] = React.useState('required');
  const [openGroups, setOpenGroups] = React.useState({ tech: true, risk: true, sop: false, capa: false });
  const [data, setData] = React.useState(null);

  const [trackId, setTrackId] = React.useState(null);
  const [sub, setSub] = React.useState(null);
  React.useEffect(() => {
    window.RAlly.resolveTrackId().then((tid) => {
      setTrackId(tid);
      if (tid) {
        fetch('/api/track/' + tid + '/cert').then((r) => r.json()).then(setData).catch(() => {});
        fetch('/api/track/' + tid + '/submission').then((r) => r.json()).then(setSub).catch(() => {});
      }
    });
  }, []);

  const toggle = (k) => setOpenGroups((p) => ({ ...p, [k]: !p[k] }));
  const cd = data || { groups: [], total: 0, done: 0, pct: 0, missing: 0 };
  const trackName = (cd.track && cd.track.name) || '트랙';

  return (
    <div className="page">
      {/* Header */}
      <div className="page__head">
        <div>
          <div className="row" style={{ gap: 8, marginBottom: 6 }}>
            <Pill variant="coral">STAGE 04 · 결승선</Pill>
            <Pill variant="navy">2등급 의료기기 + SaMD</Pill>
            <Pill>MFDS 품목허가</Pill>
          </div>
          <div className="page__title">결승선까지 같이 달려요</div>
          <div className="page__sub">
            <strong style={{ color: 'var(--ink)' }}>{trackName}</strong> · MFDS 품목허가 패키지
          </div>
        </div>
        <div className="row">
          <Button variant="primary" icon="download" disabled={!trackId} onClick={() => { if (trackId) window.location.href = '/api/track/' + trackId + '/download'; }}>패키지 다운로드 (.zip)</Button>
        </div>
      </div>

      {/* Coral banner with stat + checklist preview */}
      <div className="cert-banner" style={{ marginBottom: 8 }}>
        <div style={{ position: 'relative', zIndex: 1, maxWidth: 600 }}>
          <div className="row" style={{ gap: 8, marginBottom: 10 }}>
            <Icon name="alert" size={18} style={{ color: 'var(--coral)' }} />
            <div className="micro micro--coral">제출 준비 진행률</div>
          </div>
          <div className="cert-banner__title">필수 자료 {cd.done}개 완료, {cd.missing}개 미비</div>
          <div className="cert-banner__sub">
            완주하지 않은 문서를 채우면 제출 패키지가 자동으로 생성됩니다.
            아직 <strong>{cd.missing}개</strong>가 남아 있어요.
          </div>
          <div className="row" style={{ marginTop: 14, gap: 8 }}>
            <Button variant="accent" iconRight="arrow_right" onClick={() => go('editor')}>지금 작성하기</Button>
            <Button variant="ghost" icon="message">자문 RA 호출</Button>
          </div>
        </div>
        <div style={{ position: 'relative', zIndex: 1, textAlign: 'right' }}>
          <div className="micro" style={{ color: 'var(--ink-3)', marginBottom: 6 }}>NECESSARY DOCS</div>
          <div className="cert-banner__stat">{cd.done}<span style={{ color: 'var(--ink-3)', fontWeight: 500 }}>/{cd.total}</span></div>
          <div className="cert-banner__stat-sub">{cd.pct}% — {cd.pct >= 90 ? '결승선 직전' : '주행 중'}</div>
          <div style={{ marginTop: 12, width: 220 }}>
            <Progress value={cd.pct} />
          </div>
        </div>
      </div>

      {/* 제출 준비 패키지 — 심사구분×pillar 체크리스트 + 게이트 + 경로 (실데이터) */}
      <SubmissionPanel sub={sub} go={go} />

      {/* Track-style milestone strip (데모 전용) */}
      {window.RAlly.isDemo() && (
        <div className="card card--pad" style={{ marginBottom: 24 }}>
          <div className="between" style={{ marginBottom: 14 }}>
            <div className="section-head__title">제출 마일스톤</div>
            <div className="micro">~ 2026.09.30</div>
          </div>
          <Milestones />
        </div>
      )}

      {/* Tabs */}
      <div className="cert-tabs">
        <button className={'cert-tab' + (tab === 'required' ? ' cert-tab--active' : '')} onClick={() => setTab('required')}>
          필수 자료 <span className="cert-tab__count">· {cd.done}/{cd.total}</span>
        </button>
        <button className={'cert-tab' + (tab === 'optional' ? ' cert-tab--active' : '')} onClick={() => setTab('optional')}>
          선택 자료 <span className="cert-tab__count">· 6/8</span>
        </button>
        <button className={'cert-tab' + (tab === 'form' ? ' cert-tab--active' : '')} onClick={() => setTab('form')}>
          신청서
        </button>
        <button className={'cert-tab' + (tab === 'history' ? ' cert-tab--active' : '')} onClick={() => setTab('history')}>
          제출 이력
        </button>
      </div>

      {/* Groups (백엔드 집계) */}
      {tab === 'required' && (
        <div>
          {cd.groups.map((g) => (
            <CertGroup
              key={g.id}
              id={g.id}
              title={g.title}
              count={g.count}
              tone={g.tone}
              open={openGroups[g.id] !== false}
              onToggle={() => toggle(g.id)}
              rows={g.rows}
            />
          ))}
        </div>
      )}

      {tab === 'optional' && (
        <div className="card card--pad" style={{ textAlign: 'center', padding: 60, color: 'var(--ink-3)' }}>
          선택 자료 6/8 — 이 탭의 모킹은 생략되었어요.
        </div>
      )}
      {tab === 'form' && (
        <div className="card card--pad" style={{ textAlign: 'center', padding: 60, color: 'var(--ink-3)' }}>
          MFDS 신청서 양식 — 이 탭의 모킹은 생략되었어요.
        </div>
      )}
      {tab === 'history' && (
        <div className="card card--pad" style={{ textAlign: 'center', padding: 60, color: 'var(--ink-3)' }}>
          제출 이력 — 첫 제출 전이라 비어 있어요.
        </div>
      )}

      {/* Bottom action banner — 실제 게이트 기준 */}
      <div className="card card--pad" style={{ marginTop: 20, background: 'var(--navy)', color: 'var(--on-navy)', border: 'none' }}>
        <div className="between">
          <div className="row" style={{ gap: 14 }}>
            <Icon name="trophy" size={28} style={{ color: 'var(--coral)' }} />
            <div>
              <div style={{ fontSize: 16, fontWeight: 700 }}>
                {sub && sub.gate && sub.gate.submittable
                  ? '문서 세트가 준비됐어요 — 패키지를 내려받아 제출하세요'
                  : ((sub && sub.gate && sub.gate.summary) || '미완 문서를 채우면 제출 패키지가 자동 생성돼요')}
              </div>
              <div style={{ fontSize: 12, color: 'var(--on-navy-2)', marginTop: 2 }}>
                ZIP · 카테고리별 문서 + 요건 매핑 표. 실측·서명 등 [입력 필요] 값은 실무자가 채웁니다.
              </div>
            </div>
          </div>
          <Button variant="accent" iconRight="arrow_right" size="lg" disabled={!trackId}
            onClick={() => { if (trackId) window.location.href = '/api/track/' + trackId + '/download'; }}>패키지 다운로드</Button>
        </div>
      </div>
    </div>
  );
};

// 제출 준비 패키지 — 실데이터(/api/track/{id}/submission)
const SubmissionPanel = ({ sub, go }) => {
  if (!sub || !sub.ok) return null;
  const gate = sub.gate || {};
  const ok = gate.submittable;
  return (
    <div style={{ marginBottom: 24 }}>
      {/* 게이트 요약 */}
      <div className="card card--pad" style={{ marginBottom: 16,
        borderLeft: '4px solid ' + (ok ? 'var(--green)' : 'var(--coral)') }}>
        <div className="between">
          <div className="row" style={{ gap: 12 }}>
            <Icon name={ok ? 'check' : 'alert'} size={22} style={{ color: ok ? 'var(--green)' : 'var(--coral)' }} />
            <div>
              <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>
                {ok ? '제출 준비 완료 — 최종 RA 검토 후 제출' : '제출 전 남은 항목이 있습니다'}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 3 }}>
                {gate.summary || '문서·입력 상태를 점검하세요.'}
              </div>
            </div>
          </div>
          <div className="row" style={{ gap: 6 }}>
            {(sub.pillars || []).map((p) => <Pill key={p} variant={p === '품목허가' ? 'coral' : 'navy'}>{p}</Pill>)}
            <Pill>심사구분 · {sub.review_type}</Pill>
          </div>
        </div>
      </div>

      {/* 제출 경로 안내 */}
      <div className="card card--pad" style={{ marginBottom: 16 }}>
        <div className="section-head__title" style={{ marginBottom: 12 }}>제출 경로 안내</div>
        <div style={{ display: 'grid', gap: 10 }}>
          {(sub.routes || []).map((r, i) => (
            <div key={i} className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
              <Pill variant={r.pillar === '품목허가' ? 'coral' : 'navy'}>{r.pillar}</Pill>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{r.title}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{r.detail}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* pillar별 제출문서 체크리스트 */}
      {(sub.groups || []).map((g) => (
        <div key={g.pillar} className="card card--pad" style={{ marginBottom: 12 }}>
          <div className="between" style={{ marginBottom: 12 }}>
            <div className="row" style={{ gap: 8 }}>
              <Pill variant={g.pillar === '품목허가' ? 'coral' : 'navy'}>{g.pillar} 기둥</Pill>
              <span className="muted-2" style={{ fontSize: 12 }}>{g.ready}/{g.total} 준비완료</span>
            </div>
            <div style={{ width: 160 }}><Progress value={g.pct} size="sm" /></div>
          </div>
          <div style={{ display: 'grid', gap: 6 }}>
            {g.docs.map((d) => (
              <div key={d.code} className="row" style={{ gap: 10, padding: '6px 0', borderBottom: '1px solid var(--line)' }}>
                <div style={{ width: 20, height: 20, borderRadius: 999, display: 'grid', placeItems: 'center',
                  background: d.done ? 'var(--green-soft)' : 'var(--surface-3)',
                  color: d.done ? 'var(--green)' : 'var(--ink-3)' }}>
                  {d.done ? <Icon name="check" size={12} stroke={2.5} /> : <Icon name="file" size={11} />}
                </div>
                <div style={{ flex: 1, fontSize: 13, color: 'var(--ink)' }}>{d.label}</div>
                {d.inputs > 0 && <span className="micro micro--coral">입력 {d.inputs}</span>}
                <span style={{ fontSize: 12, fontWeight: 600,
                  color: d.done ? 'var(--green)' : 'var(--ink-3)' }}>{d.state}</span>
              </div>
            ))}
          </div>
        </div>
      ))}
      <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>{sub.note}</div>
    </div>
  );
};

const Milestones = () => {
  const items = [
    { label: '내부 검토 완료', date: '2026.06.15', state: 'done' },
    { label: '자문 RA 승인',   date: '2026.07.10', state: 'done' },
    { label: 'GMP 적합성 평가', date: '2026.08.01', state: 'current' },
    { label: 'MFDS 사전 상담', date: '2026.08.20', state: 'todo' },
    { label: '품목허가 신청',  date: '2026.09.30', state: 'todo', finish: true },
  ];
  return (
    <div style={{ position: 'relative', padding: '8px 0 20px' }}>
      <div style={{ position: 'absolute', left: 0, right: 0, top: 18, height: 4, background: 'var(--line)', borderRadius: 999 }} />
      <div style={{ position: 'absolute', left: 0, top: 18, width: '40%', height: 4, background: 'var(--coral)', borderRadius: 999 }} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', position: 'relative' }}>
        {items.map((m, i) => (
          <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <div style={{
              width: 22, height: 22, borderRadius: 999,
              background: m.state === 'done' ? 'var(--coral)' : m.state === 'current' ? 'var(--surface)' : 'var(--surface)',
              border: m.state === 'current' ? '3px solid var(--coral)' : m.state === 'done' ? '3px solid var(--coral)' : '2px solid var(--line-2)',
              boxShadow: m.state === 'current' ? '0 0 0 4px rgba(217, 96, 62, 0.18)' : 'none',
              display: 'grid', placeItems: 'center',
              color: '#fff',
            }}>
              {m.state === 'done' && <Icon name="check" size={11} stroke={2.5} />}
              {m.finish && m.state === 'todo' && <Icon name="trophy" size={11} style={{ color: 'var(--ink-3)' }} />}
            </div>
            <div style={{ fontSize: 12, fontWeight: 600, color: m.state === 'current' ? 'var(--coral)' : 'var(--ink)', textAlign: 'center' }}>{m.label}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{m.date}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const CertGroup = ({ title, count, tone, open, onToggle, rows }) => (
  <div className={'cert-group' + (tone === 'missing' ? ' cert-group--missing' : '')}>
    <div className="cert-group__head" onClick={onToggle} style={{ cursor: 'pointer' }}>
      <Icon name={open ? 'chev_down' : 'chev_right'} size={16} style={{ color: 'var(--ink-3)' }} />
      <div className="cert-group__title">{title}</div>
      <Pill variant={tone === 'missing' ? 'coral' : 'green'}>{count}</Pill>
      <span style={{ flex: 1 }} />
      <span className="muted-2" style={{ fontSize: 12 }}>{rows.length}개 항목</span>
    </div>
    {open && (
      <div>
        {rows.map((r, i) => (
          <CertRow key={i} {...r} />
        ))}
      </div>
    )}
  </div>
);

const CertRow = ({ state, title, meta, cta }) => {
  const isMissing = state === 'missing';
  return (
    <div className={'cert-row' + (isMissing ? ' cert-row--missing' : '')}>
      <div className={'cert-row__check ' + (isMissing ? 'cert-row__check--missing' : 'cert-row__check--done')}>
        {isMissing ? <Icon name="alert" size={12} stroke={2.5} /> : <Icon name="check" size={13} stroke={2.5} />}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="cert-row__title">{title}</div>
        <div className="cert-row__meta">{meta}</div>
      </div>
      {cta ? (
        <Button variant="accent" size="sm" iconRight="arrow_right">{cta}</Button>
      ) : (
        <span className="row" style={{ gap: 6, color: 'var(--ink-3)' }}>
          <Icon name="file" size={14} />
          <span style={{ fontSize: 11.5 }}>PDF</span>
        </span>
      )}
    </div>
  );
};

window.RAlly.CertPackage = CertPackage;
