/* ============================================================
   Home (project grid) + Project create/edit modal
   ============================================================ */
const { useState: useSH, useMemo: useMH } = React;

const ALL_MONTHS = Array.from({ length: 12 }, (_, i) => ({ month: i + 1, label: (i + 1) + '월' }));

/* ---------------- Project card ---------------- */
function ProjectCard({ p, isStaff, onOpen, onEdit, onStatus, onDelete }) {
  return (
    <div className="proj-card" onClick={() => onOpen(p)}>
      <div className="pc-top">
        <div style={{ minWidth: 0 }}>
          <div className="pc-name">{p.name}</div>
          <div className="pc-period"><Icon.calendar style={{ width: 13, height: 13 }} />{p.months.map((m) => m.month).join(' · ')}월</div>
        </div>
        <div className="flex center gap8">
          <StatusPill status={p.status} />
          {isStaff && (
            <Menu trigger={<button className="icon-btn" onClick={(e) => e.stopPropagation()}><Icon.dots /></button>}>
              <button onClick={() => onEdit(p)}><Icon.edit />수정</button>
              {p.status !== 'not_started' && <button onClick={() => onStatus(p, 'not_started')}><Icon.clock />시작 전</button>}
              {p.status !== 'active' && <button onClick={() => onStatus(p, 'active')}><Icon.play />진행 중</button>}
              {p.status !== 'done' && <button onClick={() => onStatus(p, 'done')}><Icon.check />완료</button>}
              <div className="menu-div" />
              <button className="danger" onClick={() => onDelete(p)}><Icon.trash />삭제</button>
            </Menu>
          )}
        </div>
      </div>

      {p.description && <div className="pc-overview">{p.description}</div>}

      <div className="pc-foot">
        {p.currentSteps && p.currentSteps.length
          ? <span className="pc-step"><span className="pc-step-dot" />현재: {p.currentSteps.map((s) => s.label).join(', ')}</span>
          : <span className="pc-step muted">단계 미지정</span>}
        <span className="flex center gap8" style={{ fontSize: 12.5, fontWeight: 650, color: 'var(--accent)' }}>열기 <Icon.arrowR style={{ width: 14, height: 14 }} /></span>
      </div>
    </div>
  );
}

/* ---------------- Home ---------------- */
function Home({ user, navigate, toast }) {
  const isStaff = user.role === 'ADMIN' || user.role === 'CNX';
  const { loading, error, data, reload, setData } = useAsync(() => window.api.getProjects(), [user.id]);
  const [form, setForm] = useSH(null); // {mode, project}
  const [confirm, setConfirm] = useSH(null);

  const stats = useMH(() => {
    const list = data || [];
    const by = (s) => list.filter((p) => p.status === s).length;
    return { total: list.length, notStarted: by('not_started'), active: by('active'), done: by('done') };
  }, [data]);

  const openProject = (p) => { if (!p.months.length) return; navigate({ name: 'project', projectId: p.id, tab: 'ops', month: p.months[0].month }); };

  const doStatus = async (p, status) => {
    await window.api.setProjectStatus(p.id, status);
    toast(`'${p.name}' → ${STATUS_LABEL[status]}`);
    reload();
  };
  const doDelete = async () => {
    const p = confirm; setConfirm(null);
    await window.api.deleteProject(p.id);
    toast(`'${p.name}' 삭제됨`); reload();
  };
  const onSaved = (saved, mode) => {
    setForm(null);
    toast(mode === 'create' ? '새 프로젝트가 생성되었습니다' : '프로젝트가 수정되었습니다');
    reload();
  };

  return (
    <div className="page-wrap">
      <div className="page-head">
        <div className="ph-row">
          <div>
            <div className="page-title">프로젝트</div>
            <div className="page-desc">{isStaff ? '운영 사이클을 등록하고 월·테마·에피소드를 관리합니다.' : '진행 중인 운영 사이클을 확인하고 에피소드를 선택·제출합니다.'}</div>
          </div>
          {isStaff && <Btn variant="primary" icon={<Icon.plus />} onClick={() => setForm({ mode: 'create' })}>새 프로젝트</Btn>}
        </div>
      </div>

      {/* stat strip */}
      {!loading && !error && (
        <div className="stat-strip">
          {[
            { v: stats.total, l: '전체 프로젝트', c: 'var(--ink)', bar: 'var(--ink-3)' },
            { v: stats.notStarted, l: '시작 전', c: 'var(--slate)', bar: 'var(--slate)' },
            { v: stats.active, l: '진행중', c: 'var(--pub-green-700)', bar: 'var(--pub-green)' },
            { v: stats.done, l: '완료', c: 'var(--cnx-blue-700)', bar: 'var(--cnx-blue)' },
          ].map((s, i) => (
            <div className="stat" key={i}><span className="sbar" style={{ background: s.bar }} /><div className="sv" style={{ color: s.c }}>{s.v}</div><div className="sl">{s.l}</div></div>
          ))}
        </div>
      )}

      {loading && <div className="proj-grid">{[0, 1, 2].map((i) => <CardSkel key={i} />)}</div>}
      {error && <ErrorState onRetry={reload} msg={error} />}

      {!loading && !error && data.length === 0 && (
        <EmptyState icon={<Icon.grid />} title="프로젝트가 없습니다"
          desc={isStaff ? '첫 운영 사이클을 만들어 시작하세요.' : '현재 진행 중인 프로젝트가 없습니다. 운영팀(CNX)에 문의하세요.'}
          action={isStaff ? <Btn variant="primary" icon={<Icon.plus />} onClick={() => setForm({ mode: 'create' })}>새 프로젝트</Btn> : null} />
      )}

      {!loading && !error && data.length > 0 && (
        <div className="proj-grid">
          {data.map((p) => (
            <ProjectCard key={p.id} p={p} isStaff={isStaff} onOpen={openProject}
              onEdit={(p) => setForm({ mode: 'edit', project: p })} onStatus={doStatus} onDelete={(p) => setConfirm(p)} />
          ))}
          {isStaff && (
            <button className="new-proj-card" onClick={() => setForm({ mode: 'create' })}>
              <span className="npc-ic"><Icon.plus /></span>
              <span style={{ fontWeight: 700, fontSize: 13.5 }}>새 프로젝트</span>
              <span style={{ fontSize: 12 }}>운영 사이클 추가</span>
            </button>
          )}
        </div>
      )}

      {form && <ProjectForm mode={form.mode} project={form.project} onClose={() => setForm(null)} onSaved={onSaved} />}
      {confirm && (
        <Modal title="프로젝트 삭제" sub={`'${confirm.name}'`} onClose={() => setConfirm(null)}
          footer={<><Btn onClick={() => setConfirm(null)}>취소</Btn><Btn variant="primary" icon={<Icon.trash />} onClick={doDelete}>삭제</Btn></>}>
          <p style={{ color: 'var(--ink-2)' }}>이 프로젝트와 연결된 테마·에피소드·선택·제출 데이터가 모두 삭제됩니다. 이 작업은 되돌릴 수 없습니다.</p>
        </Modal>
      )}
    </div>
  );
}

/* ---------------- Project create / edit ---------------- */
function ProjectForm({ mode, project, onClose, onSaved }) {
  const [name, setName] = useSH(project?.name || '');
  const [status, setStatus] = useSH(project?.status || 'not_started');
  const [months, setMonths] = useSH(() => new Set((project?.months || []).map((m) => m.month)));
  const [desc, setDesc] = useSH(project?.description || '');
  const [busy, setBusy] = useSH(false);
  const [err, setErr] = useSH('');

  const toggleMonth = (m) => setMonths((prev) => {
    const next = new Set(prev);
    if (next.has(m)) next.delete(m); else next.add(m);
    return next;
  });

  const save = async () => {
    if (!name.trim()) return setErr('프로젝트 이름을 입력하세요.');
    const monthArr = [...months].sort((a, b) => a - b);
    if (!monthArr.length) return setErr('포함할 월을 1개 이상 선택하세요.');
    setBusy(true); setErr('');
    const body = {
      name: name.trim(), status, description: desc.trim() || undefined,
      months: monthArr.map((m) => ({ month: m, label: m + '월' })),
    };
    try {
      const saved = mode === 'create' ? await window.api.createProject(body) : await window.api.updateProject(project.id, body);
      if (mode === 'edit' && status !== project.status) await window.api.setProjectStatus(project.id, status);
      onSaved(saved, mode);
    } catch (e) { setErr(e.message); setBusy(false); }
  };

  return (
    <Modal wide title={mode === 'create' ? '새 프로젝트' : '프로젝트 수정'} sub="운영 사이클의 이름·개요·포함 월을 설정합니다." onClose={onClose}
      footer={<><Btn onClick={onClose}>취소</Btn><Btn variant="primary" onClick={save} disabled={busy} icon={busy ? <Icon.clock className="spin" /> : <Icon.check />}>{mode === 'create' ? '생성' : '저장'}</Btn></>}>
      <div className="frow">
        <label className="flabel">프로젝트 이름</label>
        <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="예: LG AI 365 — 8·9월 캠페인" />
      </div>
      <div className="frow">
        <label className="flabel">개요 <span style={{ fontWeight: 500, color: 'var(--ink-3)' }}>(선택)</span></label>
        <textarea className="textarea" value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="이 운영 사이클에 대한 간단한 설명" rows={2} />
      </div>
      <div className="frow">
        <label className="flabel">포함할 월</label>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
          {ALL_MONTHS.map((m) => {
            const on = months.has(m.month);
            return (
              <div key={m.month} className={`month-chip ${on ? 'on' : ''}`} onClick={() => toggleMonth(m.month)}>
                <span className="ep-check" style={{ position: 'static', width: 20, height: 20 }}>
                  {on && <Icon.check style={{ width: 13, height: 13, color: 'var(--accent)' }} />}
                </span>
                <span className="mc-name">{m.label}</span>
              </div>
            );
          })}
        </div>
        <p className="fhint">이 운영 사이클에 포함할 월을 선택합니다. 에피소드 제출은 월별 수량 제한 없이 자유롭게 진행됩니다.</p>
      </div>
      <div className="frow">
        <label className="flabel">상태</label>
        <select className="select" value={status} onChange={(e) => setStatus(e.target.value)}>
          <option value="not_started">시작 전</option>
          <option value="active">진행 중</option>
          <option value="done">완료</option>
        </select>
        <p className="fhint">LGE에게는 '진행 중' 프로젝트만 노출됩니다.</p>
      </div>
      {err && <div className="login-err" style={{ marginTop: 4 }}>{err}</div>}
    </Modal>
  );
}

Object.assign(window, { Home, ProjectForm });
