/* SEAL — Core flow pages: ④예실대비(home) ⑤인박스 ⑥AI제안 ⑦집행 ⑧서류 */
const { useState, useEffect, useRef } = React;
const F2 = window.SEAL_FMT;
const D = window.SEAL_DATA;

/* ========================================================================
   ④ 예실대비 (홈, /) — 중심
   ===================================================================== */
function HomePage({ nav, live }) {
  const { total, spent, remain, items } = live;
  const active = items.filter((i) => i.active);
  const inactive = items.filter((i) => !i.active);
  const recent = live.executions || [];

  return (
    <div className="page fade-in">
      <PageHead
        eyebrow="예실대비 · 한눈에"
        title="연구만 하세요. 회계는 AI가."
        sub={<>{D.project.title}</>}
        action={<Btn icon="plus" size="lg" onClick={() => nav("inbox")}>새 집행</Btn>}
      />

      {/* 문장형 요약 */}
      <div className="card" style={{ marginBottom: 20, display: "flex", gap: 16, alignItems: "center" }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--semantic-primary-normal)", display: "grid", placeItems: "center", color: "#fff", flexShrink: 0 }}>
          <Icons.sparkles size={24} />
        </div>
        <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.5 }} className="tnum">
          지금까지 <b style={{ color: "var(--semantic-primary-normal)" }}>{F2.manwon(total)}</b> 중{" "}
          <b style={{ color: "var(--semantic-primary-normal)" }}>{F2.manwon(spent)}</b> 썼고,{" "}
          <b style={{ color: "var(--semantic-primary-normal)" }}>{F2.manwon(remain)}</b> 쓸 수 있어요.
        </div>
      </div>

      {/* KPI 3 */}
      <div className="kpis" style={{ marginBottom: 32 }}>
        <Kpi label="총예산" icon="wallet" value={F2.manwon(total)} foot="혁신법 연구비 협약 기준" />
        <Kpi label="집행" icon="bolt" value={F2.manwon(spent)} foot={`전체의 ${F2.pct(spent, total)}%`} />
        <Kpi label="쓸 수 있음 (잔액)" icon="coins" value={F2.manwon(remain)} foot="집행 가능 6비목 합산" accent />
      </div>

      {/* 비목별 막대 */}
      <SecHead title="비목별 예실대비" link="예산안 전체 보기" onLink={() => nav("budget")} />
      <div className="card" style={{ marginBottom: 16 }}>
        <div className="barlist">
          {active.map((it) => <BudgetBar key={it.name} item={it} onClick={() => nav("budget")} />)}
        </div>
      </div>
      {inactive.length > 0 && (
        <div className="card" style={{ marginBottom: 32 }}>
          <div className="row" style={{ gap: 8, marginBottom: 4 }}>
            <Icons.clock size={16} />
            <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--semantic-label-alternative)" }}>다른 비목</span>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 12 }}>
            {inactive.map((it) => (
              <span key={it.name} className="badge badge-gray" style={{ height: 30, fontSize: 13 }}>
                {it.name} · {F2.manwon(it.budget)}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* 최근 집행 이력 */}
      <SecHead title="최근 집행 이력" link="전체 이력" onLink={() => nav("history")} />
      <div className="card flush">
        {recent.length === 0 ? (
          <Empty icon="bolt" title="아직 집행 내역이 없어요">
            팀 대화에서 니즈를 불러와 첫 집행을 시작해 보세요.
          </Empty>
        ) : recent.map((ex, i) => (
          <div className="lrow" key={i}>
            <div className="lrow-icon blue"><CategoryIcon cat={ex.category} /></div>
            <div className="lrow-body">
              <div className="lrow-title">{ex.summary}</div>
              <div className="lrow-meta">{ex.categoryName} · {ex.at} · 서류 {ex.docCount}건</div>
            </div>
            <div className="lrow-right">
              <div className="mono-won tnum" style={{ fontSize: 15 }}>{F2.won(ex.totalKRW)}</div>
              <div style={{ marginTop: 5 }}><VerdictBadge verdict={ex.verdict} /></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function CategoryIcon({ cat, size = 20 }) {
  const m = { "travel-overseas": "plane", "travel-domestic": "plane", "materials": "cpu", "supplies": "bag", "meeting": "coins" };
  const I = Icons[m[cat] || "bolt"];
  return <I size={size} />;
}

/* ========================================================================
   ⑤ 대화 인박스 (/inbox)
   ===================================================================== */
function InboxPage({ nav, store, setStore }) {
  const [loading, setLoading] = useState(false);
  const [loaded, setLoaded] = useState(store.inboxLoaded || false);
  const [open, setOpen] = useState(null);

  const loadSamples = () => {
    setLoading(true);
    setTimeout(() => { setLoading(false); setLoaded(true); setStore((s) => ({ ...s, inboxLoaded: true })); }, 900);
  };

  const process = (conv) => {
    setStore((s) => ({ ...s, activeNeeds: conv.needs, activeConv: conv.id }));
    toast("니즈 2건을 AI 제안으로 보냈어요", true);
    nav("propose");
  };

  return (
    <div className="page fade-in">
      <PageHead
        eyebrow="대화 인박스"
        title="팀 대화에서 집행할 일을 찾아요"
        sub="카카오톡 .txt 나 전화 STT를 올리면, AI가 혁신법 비목에 맞는 니즈를 감지해요. 사람은 확인만 하면 돼요."
        action={!loaded
          ? <Btn icon="inbox" size="lg" variant="soft" onClick={loadSamples}>샘플 대화 불러오기</Btn>
          : <Btn icon="plus" size="lg" variant="outline" onClick={loadSamples}>새로고침</Btn>}
      />

      {loading && (
        <div className="card" style={{ marginBottom: 14 }}>
          <Skel h={18} w="40%" style={{ marginBottom: 14 }} />
          <Skel h={14} w="90%" style={{ marginBottom: 8 }} />
          <Skel h={14} w="70%" />
        </div>
      )}

      {!loaded && !loading && (
        <div className="card">
          <Empty icon="inbox" title="아직 불러온 대화가 없어요">
            샘플 대화를 불러오면 AI가 니즈를 감지하는 과정을 볼 수 있어요.
          </Empty>
        </div>
      )}

      {loaded && !loading && (
        <div className="stack" style={{ gap: 16 }}>
          {D.conversations.map((conv) => (
            <div className="card flush" key={conv.id}>
              {/* head */}
              <div className="row" style={{ gap: 12, padding: "18px 20px", borderBottom: "1px solid var(--semantic-line-normal-alternative)" }}>
                <div className="lrow-icon">{conv.source === "audio" ? <Icons.phone size={19} /> : <Icons.chat size={19} />}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="row" style={{ gap: 7 }}>
                    <span style={{ fontWeight: 700, fontSize: 14.5 }}>{conv.room}</span>
                    <Badge tone="gray">{conv.channel}</Badge>
                    {conv.unread && <Badge tone="blue" dot>NEW</Badge>}
                  </div>
                  <div className="lrow-meta">{conv.filename} · {conv.at}</div>
                </div>
                <Btn size="sm" variant="ghost" iconRight={open === conv.id ? "chevDown" : "chevRight"} onClick={() => setOpen(open === conv.id ? null : conv.id)}>
                  대화 {open === conv.id ? "접기" : "보기"}
                </Btn>
              </div>

              {/* transcript */}
              {open === conv.id && (
                <div className="fade-in" style={{ padding: "16px 20px", background: "var(--semantic-fill-alternative)", borderBottom: "1px solid var(--semantic-line-normal-alternative)" }}>
                  {conv.lines.map((ln, i) => (
                    <div key={i} style={{ display: "flex", gap: 10, marginBottom: 10 }}>
                      <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--semantic-label-neutral)", minWidth: 76, flexShrink: 0 }}>{ln.who}</span>
                      <span style={{ fontSize: 13.5, color: "var(--semantic-label-normal)", lineHeight: 1.5, flex: 1 }}>{ln.t}</span>
                      <span style={{ fontSize: 11.5, color: "var(--semantic-label-assistive)", flexShrink: 0 }}>{ln.at}</span>
                    </div>
                  ))}
                </div>
              )}

              {/* detected needs */}
              <div style={{ padding: "16px 20px" }}>
                <div className="row" style={{ gap: 7, marginBottom: 12 }}>
                  <Icons.sparkles size={16} color="var(--semantic-primary-normal)" />
                  <span style={{ fontSize: 13, fontWeight: 700, color: "var(--semantic-primary-normal)" }}>AI가 감지한 니즈 {conv.needs.length}건</span>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {conv.needs.map((n, i) => (
                    <div key={i} className="row" style={{ gap: 12, padding: "12px 14px", border: "1px solid var(--semantic-line-normal-neutral)", borderRadius: 12 }}>
                      <span className="chip need"><CategoryIcon cat={n.category} size={15} />{n.categoryName}</span>
                      <span style={{ flex: 1, fontSize: 14, fontWeight: 500, lineHeight: 1.45 }}>{n.summary}</span>
                    </div>
                  ))}
                </div>
                <div style={{ marginTop: 16 }}>
                  <Btn icon="sparkles" iconRight="arrowRight" onClick={() => process(conv)}>이 대화 처리하기</Btn>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ========================================================================
   ⑥ AI 제안 (/propose) — AI① 접점
   ===================================================================== */
function ProposePage({ nav, store, setStore }) {
  const needs = store.activeNeeds || D.conversations[0].needs;
  return (
    <div className="page fade-in">
      <PageHead
        eyebrow="AI 제안 · AI① 접점"
        title="규정에 맞춰 집행안을 만들었어요"
        sub="비목 매칭 · 상품 검색 · 예산 적합성 · 여비 기준(공무원 vs 자체규정)을 모두 검토했어요. 승인만 하면 집행으로 넘어가요."
      />
      <div className="stack" style={{ gap: 20 }}>
        {needs.map((need) => (
          <ProposalCard key={need.category} need={need} store={store} setStore={setStore} nav={nav} />
        ))}
      </div>
    </div>
  );
}

function ProposalCard({ need, store, setStore, nav }) {
  const p = D.proposals[need.category];
  if (!p) return null;
  const approved = !!(store.approved && store.approved[need.category]);
  const subtotal = p.offers.reduce((a, o) => a + o.price, 0);

  const approve = () => {
    setStore((s) => ({ ...s, approved: { ...(s.approved || {}), [need.category]: { ...p, subtotal } } }));
    toast(`${p.categoryName} 집행안을 승인했어요`, true);
  };

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden", borderColor: approved ? "var(--atomic-green-50)" : undefined }}>
      {/* header */}
      <div className="row" style={{ gap: 12, padding: "20px 24px", borderBottom: "1px solid var(--semantic-line-normal-alternative)" }}>
        <div className="lrow-icon blue" style={{ width: 44, height: 44 }}><CategoryIcon cat={need.category} size={22} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="row" style={{ gap: 8 }}>
            <span className="card-title">{p.categoryName}</span>
            <VerdictBadge verdict={p.verdict} />
          </div>
          <div className="card-sub">{p.need}</div>
        </div>
        {approved && <Badge tone="green" dot>승인됨</Badge>}
      </div>

      <div style={{ padding: "20px 24px", display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 24 }}>
        {/* left: offers */}
        <div>
          <div className="row" style={{ gap: 7, marginBottom: 12 }}>
            <Icons.search size={15} color="var(--semantic-label-alternative)" />
            <span style={{ fontSize: 13, fontWeight: 700, color: "var(--semantic-label-alternative)" }}>상품 검색 결과 · 가격순</span>
          </div>
          <div className="stack" style={{ gap: 10 }}>
            {p.offers.map((o, i) => (
              <div key={i} className="row" style={{ gap: 12, padding: "13px 14px", border: "1px solid var(--semantic-line-normal-neutral)", borderRadius: 12 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="row" style={{ gap: 6, marginBottom: 4 }}>
                    <Badge tone={o.provider === "MyRealTrip" ? "blue" : "gray"}>{o.provider}</Badge>
                    <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--semantic-label-assistive)" }}>{o.kind}</span>
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.4 }}>{o.name}</div>
                  <div className="lrow-meta">{o.vendor} · {o.meta}</div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6, whiteSpace: "nowrap" }}>
                  <div className="mono-won tnum" style={{ fontSize: 15 }}>{F2.won(o.price)}</div>
                  <a
                    href={(() => {
                      if (o.landingUrl && o.landingUrl !== "#") return o.landingUrl;
                      if (o.url || o.bookingUrl || o.link) return o.url || o.bookingUrl || o.link;
                      const q = encodeURIComponent(o.name || o.vendor || "");
                      if (o.provider === "MyRealTrip") return /항공|항공권|flight/i.test((o.kind || "") + (o.name || "")) ? "https://flights.myrealtrip.com/" : "https://www.myrealtrip.com/";
                      if (o.provider === "다나와") return "https://search.danawa.com/dsearch.php?query=" + q;
                      if (o.provider === "다이소") return "https://www.daisomall.co.kr/ds/search?keyword=" + q;
                      if (o.provider === "쿠팡" || o.provider === "Coupang") return "https://www.coupang.com/np/search?q=" + q;
                      return "https://www.coupang.com/np/search?q=" + q; // API Fuse·기타 소모품 → 쿠팡 검색
                    })()}
                    target="_blank"
                    rel="noreferrer"
                    onClick={(e) => e.stopPropagation()}
                    style={{ fontSize: 11.5, fontWeight: 700, color: "var(--semantic-primary-normal)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 3 }}
                  >
                    {o.provider === "MyRealTrip" ? "예약하러 가기" : "구매하러 가기"} ↗
                  </a>
                </div>
              </div>
            ))}
          </div>
          <div className="row" style={{ justifyContent: "space-between", marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--semantic-line-normal-alternative)" }}>
            <span style={{ fontSize: 14, fontWeight: 700 }}>예상 집행 합계</span>
            <span className="mono-won tnum" style={{ fontSize: 18, color: "var(--semantic-primary-normal)" }}>{F2.won(subtotal)}</span>
          </div>
        </div>

        {/* right: budget + allowance + reasons */}
        <div className="stack" style={{ gap: 16 }}>
          {/* budget match */}
          <div style={{ padding: "14px 16px", background: "var(--semantic-fill-alternative)", borderRadius: 12 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--semantic-label-alternative)", marginBottom: 8 }}>예산 매칭</div>
            <div className="tnum" style={{ fontSize: 14, lineHeight: 1.6 }}>
              {p.categoryName} <b>{F2.manwon(p.budget.plan)}</b> 중 <b>{F2.manwon(p.budget.estimate)}</b>
              <Badge tone="green" dot>예산 내 {p.budget.fit}</Badge>
            </div>
          </div>

          {/* allowance compare */}
          {p.allowance && (
            <div style={{ padding: "14px 16px", border: "1px solid var(--semantic-line-normal-neutral)", borderRadius: 12 }}>
              <div className="row" style={{ gap: 6, marginBottom: 10 }}>
                <Icons.scale size={15} color="var(--semantic-label-alternative)" />
                <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--semantic-label-alternative)" }}>여비 기준 비교</span>
              </div>
              <table className="tbl" style={{ fontSize: 12.5 }}>
                <thead><tr>
                  <th style={{ padding: "6px 8px", background: "none" }}> </th>
                  <th className="num" style={{ padding: "6px 8px", background: "none" }}>공무원</th>
                  <th className="num" style={{ padding: "6px 8px", background: "none" }}>자체규정</th>
                </tr></thead>
                <tbody>
                  {[["일비", "일비"], ["숙박상한", "숙박상한"], ["식비", "식비"]].map(([k, label]) => (
                    <tr key={k}>
                      <td style={{ padding: "6px 8px" }}>{label}</td>
                      <td className="num" style={{ padding: "6px 8px" }}>${p.allowance.공무원[k]}</td>
                      <td className="num" style={{ padding: "6px 8px", fontWeight: 700, color: "var(--semantic-primary-normal)" }}>${p.allowance.자체[k]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div style={{ fontSize: 12.5, color: "var(--semantic-label-neutral)", marginTop: 10, lineHeight: 1.5, fontWeight: 600 }}>
                적용: {p.allowance.적용}
              </div>
            </div>
          )}

          {/* reasons */}
          <div>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--semantic-label-alternative)", marginBottom: 8 }}>판단 근거</div>
            <ul style={{ margin: 0, paddingLeft: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 7 }}>
              {p.reasons.map((r, i) => (
                <li key={i} className="row" style={{ gap: 8, alignItems: "flex-start", fontSize: 13, lineHeight: 1.5 }}>
                  <Icons.check size={15} color="var(--atomic-green-40)" style={{ flexShrink: 0, marginTop: 2 }} />
                  <span>{r}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>

      {/* 근거 조문 strip */}
      <div style={{ padding: "14px 24px", background: "var(--semantic-fill-alternative)", borderTop: "1px solid var(--semantic-line-normal-alternative)", display: "flex", flexWrap: "wrap", gap: 8 }}>
        {p.근거.map((g, i) => (
          <span key={i} className="badge badge-gray" style={{ background: "#fff", border: "1px solid var(--semantic-line-normal-normal)" }}><b style={{ color: "var(--semantic-label-neutral)" }}>{g.layer}</b> · {g.ref}</span>
        ))}
      </div>

      {/* actions */}
      <div className="row" style={{ gap: 10, padding: "16px 24px", justifyContent: "flex-end", borderTop: "1px solid var(--semantic-line-normal-alternative)" }}>
        <Btn variant="outline" icon="edit" onClick={() => toast("수정 화면은 데모에서 생략되었어요")}>수정</Btn>
        {approved
          ? <Btn variant="primary" iconRight="arrowRight" onClick={() => nav("execute")}>집행으로 이동</Btn>
          : <Btn variant="primary" icon="check" onClick={approve}>승인</Btn>}
      </div>
    </div>
  );
}

window.CorePages = { HomePage, InboxPage, ProposePage, CategoryIcon };
window.CategoryIcon = CategoryIcon;
