// OLLYMEN Store OS — New Store Opening Board
const { useState: useStateOpen } = React;

function OpeningBoard() {
  const D = window.DATA;
  const [pick, setPick] = useStateOpen("sy");
  const store = D.stores.find(s => s.id === pick);

  // Count states
  const allTasks = D.openingBoard.flatMap(p => p.tasks);
  const counts = {
    done: allTasks.filter(t => t.state === "done").length,
    doing: allTasks.filter(t => t.state === "doing").length,
    blocked: allTasks.filter(t => t.state === "blocked").length,
    todo: allTasks.filter(t => t.state === "todo").length,
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
            <span className="mono" style={{ fontSize: 11, color: "var(--muted)", letterSpacing: ".08em", textTransform: "uppercase" }}>NEW STORE OPENING</span>
            <StatusBadge kind="opening" />
            <span className="mono" style={{ fontSize: 12, fontWeight: 600, color: "var(--burnt)" }}>D-18</span>
          </div>
          <div className="page-h1">서울역그랜드점 · 오픈 보드</div>
          <div className="page-sub">오픈 예정 2026.06.12 (금) · 17 마일스톤 · 담당자 4명 · 강남 기준 운영 SOP 적용</div>
        </div>
        <div className="page-right">
          {/* Store switch */}
          <div style={{ display: "inline-flex", padding: 3, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 8 }}>
            <SwitchBtn label="서울역그랜드점" sub="오픈 D-18" active={pick === "sy"} onClick={() => setPick("sy")} />
            <SwitchBtn label="판교역점" sub="확장 후보" active={pick === "pg"} onClick={() => setPick("pg")} />
          </div>
          <button className="tb-btn">{I.copy()} 강남 SOP 복제</button>
          <button className="btn primary">{I.plus()} 마일스톤 추가</button>
        </div>
      </div>

      {pick === "sy" ? (
        <>
          {/* Top summary */}
          <div className="grid g-4 rise d1" style={{ marginBottom: 16 }}>
            <Metric k="전체 준비율" v="64" unit="%" accent="burnt" sub="11 / 17 완료" />
            <Metric k="오픈까지" v="18" unit="일" accent="ramen" sub="2026.06.12 (금)" />
            <Metric k="진행 중 / 지연" v={`${counts.doing} / ${counts.blocked}`} sub="POS 설치 D+2 지연 1건" />
            <Metric k="배정된 직원" v="3" unit="명" accent="olive" sub="채용 4명 진행 중 · 교육 평균 47%" />
          </div>

          {/* Pre-opening checklist with 4 columns by phase */}
          <div className="card rise d2" style={{ marginBottom: 16 }}>
            <CardHead
              title="오픈 준비 보드"
              sub="4 페이즈 · 17 마일스톤 · 담당자별 마감일 관리"
              right={
                <div style={{ display: "flex", gap: 6 }}>
                  <Legend dot="var(--success)" label={`완료 ${counts.done}`} />
                  <Legend dot="var(--burnt)" label={`진행 ${counts.doing}`} />
                  <Legend dot="var(--danger)" label={`지연 ${counts.blocked}`} />
                  <Legend dot="var(--muted)" label={`예정 ${counts.todo}`} />
                </div>
              }
            />
            <div style={{ padding: 14, background: "var(--bg-2)" }}>
              <div className="grid kanban-scroll" style={{ gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
                {D.openingBoard.map((col, ci) => (
                  <div key={ci} style={{
                    background: "var(--surface)",
                    border: "1px solid var(--line)",
                    borderRadius: 10,
                    overflow: "hidden",
                  }}>
                    <div style={{
                      padding: "10px 12px",
                      borderBottom: "1px solid var(--line-soft)",
                      background: phaseTint(col.color),
                      display: "flex", alignItems: "center", gap: 8,
                    }}>
                      <span style={{ width: 8, height: 8, borderRadius: 2, background: phaseDot(col.color) }}></span>
                      <span style={{ fontWeight: 650, fontSize: 13 }}>{col.phase}</span>
                      <span className="mono" style={{ marginLeft: "auto", fontSize: 11, color: "var(--muted)" }}>{col.tasks.length}</span>
                    </div>
                    <div style={{ padding: 8, display: "flex", flexDirection: "column", gap: 6 }}>
                      {col.tasks.map(t => <TaskCard key={t.id} t={t} />)}
                      <button className="btn sm ghost" style={{ marginTop: 4, justifyContent: "flex-start" }}>{I.plus()} 새 마일스톤</button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Bottom: timeline + supply contract */}
          <div className="grid rise d3" style={{ gridTemplateColumns: "1.5fr 1fr", gap: 16 }}>
            <div className="card">
              <CardHead title="오픈 타임라인" sub="3주 · 주차별 마일스톤" />
              <div className="card-b">
                <Timeline />
              </div>
            </div>

            <div className="card">
              <CardHead title="공급망 & 인프라" sub="공급사 / 계약 상태" />
              <div className="card-b">
                <table className="tbl">
                  <tbody>
                    {[
                      { k: "올리브오일 (Frantoio)", v: "Olio Bottega", s: "계약", pill: "ok" },
                      { k: "조개 · 닭 육수 라인", v: "자가생산", s: "준비", pill: "ok" },
                      { k: "타마고면", v: "Mokpo Noodle", s: "계약", pill: "ok" },
                      { k: "토마토 베이스", v: "Sungwoo F&B", s: "계약", pill: "ok" },
                      { k: "POS · Toast", v: "Toast Korea", s: "지연 D+2", pill: "warn" },
                      { k: "배달앱 (배민·쿠팡)", v: "본사", s: "대기", pill: "warn" },
                      { k: "네이버 플레이스", v: "본사", s: "대기", pill: "warn" },
                    ].map((r, i) => (
                      <tr key={i}>
                        <td style={{ fontWeight: 600, fontSize: 12.5 }}>{r.k}</td>
                        <td className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>{r.v}</td>
                        <td><span className={`pill ${r.pill}`}>{r.s}</span></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </>
      ) : (
        <PangyoScoutView />
      )}
    </div>
  );
}

function SwitchBtn({ label, sub, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      padding: "5px 12px",
      borderRadius: 6,
      background: active ? "var(--ink)" : "transparent",
      color: active ? "oklch(0.96 0.01 70)" : "var(--ink-2)",
      fontSize: 12, fontWeight: 600,
      display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 0,
    }}>
      {label}
      <span className="mono" style={{ fontSize: 10, opacity: .65, fontWeight: 500 }}>{sub}</span>
    </button>
  );
}

function Legend({ dot, label }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, color: "var(--ink-2)", padding: "3px 8px", background: "var(--surface-2)", borderRadius: 999, border: "1px solid var(--line-soft)" }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: dot }}></span>
      {label}
    </span>
  );
}

function phaseTint(c) {
  return { ramen: "var(--ramen-wash)", olive: "var(--olive-wash)", burnt: "var(--burnt-wash)", ink: "var(--surface-2)" }[c];
}
function phaseDot(c) {
  return { ramen: "var(--ramen)", olive: "var(--olive)", burnt: "var(--burnt)", ink: "var(--ink-2)" }[c];
}

function TaskCard({ t }) {
  const stateConf = {
    done:    { tag: "완료",  cls: "ok",    border: "var(--line-soft)" },
    doing:   { tag: "진행",  cls: "warn",  border: "oklch(0.86 0.07 60)" },
    blocked: { tag: "지연",  cls: "low",   border: "oklch(0.85 0.05 30)" },
    todo:    { tag: "예정",  cls: "",      border: "var(--line-soft)" },
  };
  const c = stateConf[t.state];
  return (
    <div style={{
      padding: "10px 11px",
      borderRadius: 8,
      background: t.state === "blocked" ? "var(--danger-wash)" : "var(--surface-2)",
      border: `1px solid ${c.border}`,
    }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 8 }}>
        <Check checked={t.state === "done"} size={16} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: t.state === "done" ? "var(--muted)" : "var(--ink)", textDecoration: t.state === "done" ? "line-through" : "none" }}>{t.title}</div>
          {t.note && <div className="mono" style={{ fontSize: 11, color: "var(--danger)", marginTop: 3 }}>⚠ {t.note}</div>}
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 8, fontSize: 11, color: "var(--muted)" }}>
        <div className="avatar sm" style={{ width: 18, height: 18, fontSize: 9 }}>{t.owner.slice(0, 1)}</div>
        <span style={{ fontWeight: 600, color: "var(--ink-2)" }}>{t.owner}</span>
        <span className="mono" style={{ marginLeft: "auto" }}>{t.due}</span>
        <span className={`pill ${c.cls}`} style={{ fontSize: 10 }}>{c.tag}</span>
      </div>
    </div>
  );
}

function Timeline() {
  const weeks = [
    { label: "W21 · 5/19", milestones: [
      { day: 0, t: "주방 입고", state: "done" },
      { day: 2, t: "냉장고 시운전", state: "done" },
      { day: 1, t: "유니폼 사이즈", state: "done" },
    ]},
    { label: "W22 · 5/26", milestones: [
      { day: 0, t: "POS 설치", state: "blocked" },
      { day: 3, t: "홀 4명 채용 마감", state: "doing" },
      { day: 4, t: "합동 교육 1회차", state: "doing" },
      { day: 5, t: "초도 발주", state: "todo" },
    ]},
    { label: "W23 · 6/2", milestones: [
      { day: 1, t: "오픈 리허설 1", state: "todo" },
      { day: 3, t: "콘텐츠 촬영", state: "todo" },
      { day: 5, t: "오픈 리허설 2", state: "todo" },
      { day: 6, t: "그랜드 오픈", state: "todo", flag: true },
    ]},
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
      {weeks.map((w, wi) => (
        <div key={wi}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <span className="mono" style={{ fontSize: 11, fontWeight: 600, color: "var(--muted)" }}>{w.label}</span>
            <div style={{ flex: 1, height: 1, background: "var(--line)" }}></div>
          </div>
          <div style={{ position: "relative", paddingLeft: 18 }}>
            <div style={{ position: "absolute", left: 5, top: 4, bottom: 4, width: 2, background: "var(--line)" }}></div>
            {w.milestones.map((m, mi) => (
              <div key={mi} style={{ position: "relative", padding: "6px 0" }}>
                <div style={{
                  position: "absolute", left: -16, top: 9, width: 10, height: 10, borderRadius: "50%",
                  background: m.state === "done" ? "var(--olive)" : m.state === "blocked" ? "var(--danger)" : m.state === "doing" ? "var(--burnt)" : "var(--surface)",
                  border: m.state === "todo" ? "2px solid var(--line-strong)" : "2px solid var(--surface)",
                  boxShadow: m.flag ? "0 0 0 3px oklch(0.86 0.04 30)" : "none",
                }}></div>
                <div style={{ fontSize: 12.5, fontWeight: m.flag ? 700 : 600, color: m.flag ? "var(--ramen)" : "var(--ink)" }}>{m.t}</div>
                <div className="mono" style={{ fontSize: 10.5, color: "var(--muted)" }}>{wi === 0 ? "5/" + (19 + m.day) : wi === 1 ? "5/" + (26 + m.day) : "6/" + (2 + m.day)}</div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function PangyoScoutView() {
  return (
    <div className="grid" style={{ gridTemplateColumns: "1.4fr 1fr", gap: 16 }}>
      <div className="card rise d1">
        <CardHead title="상권 분석 — 판교역" sub="확장 후보 · 상권 검토 단계" />
        <div className="card-b">
          <div className="grid g-3" style={{ marginBottom: 14 }}>
            <Metric k="예상 일평균 객수" v="180" unit="명" sub="강남 +27%" />
            <Metric k="직장인 점심 비중" v="74" unit="%" sub="11:30 – 13:30 집중" />
            <Metric k="유사 매장 밀도" v="3" unit="개" sub="반경 300m 라멘·우동" />
          </div>
          <Placeholder label="상권 지도 · Naver Maps 연동 (v1.5)" height={220} />
          <div className="kv" style={{ marginTop: 16 }}>
            <span className="k">예상 임대 단가</span><span>월 1,250만원 · 24평 1층</span>
            <span className="k">고객 평균 객단가</span><span>14,200원 (강남 동일 가정)</span>
            <span className="k">예상 오픈</span><span>2026 Q3 · 검토 완료 후 D-90 착수</span>
            <span className="k">메뉴 적합도</span><span>매운맛 선호 ↑ — 카라이 라멘 비중 +5% 가정</span>
          </div>
        </div>
      </div>

      <div className="col" style={{ gap: 16 }}>
        <div className="card rise d2">
          <CardHead title="검토 체크리스트" sub="확장 진행 전 통과 조건" />
          <div className="card-b">
            {[
              { t: "상권 데이터 수집 (3사)", done: true },
              { t: "직장인 점심 수요 검증", done: true },
              { t: "유사 매장 가격 · 회전 조사", done: true },
              { t: "임대 협상", done: false },
              { t: "본사 결재", done: false },
              { t: "운영 SOP 적합도 검증", done: false },
              { t: "신규 채용 계획 수립", done: false },
            ].map((c, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: i < 6 ? "1px dashed var(--line-soft)" : 0 }}>
                <Check checked={c.done} size={16} />
                <span style={{ flex: 1, fontSize: 13, color: c.done ? "var(--muted)" : "var(--ink)", textDecoration: c.done ? "line-through" : "none" }}>{c.t}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="card rise d3">
          <CardHead title="대표 메모" />
          <div className="card-b" style={{ fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)" }}>
            "판교는 강남과 객층은 유사하지만 점심 비중이 더 높다. 마라/카라이의 매운맛 라인을 강조한 운영을 가정한다. 임대 협상 후 본사 결재 들어갈 예정."
            <div className="mono" style={{ fontSize: 11, color: "var(--muted)", marginTop: 6 }}>고대수 · 2026.05.20</div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.OpeningBoard = OpeningBoard;
