/* ============================================================
   analysis.jsx — 결제 기반 심층 분석 화면
   ============================================================ */
const { useState: anS, useEffect: anE, useMemo: anM } = React;

const API_BASE = "https://sajuproject-3uv2.onrender.com";

const ANALYSIS_TOPICS = [
  { id: "daeun", label: "현재 대운 해석", emoji: "🌊" },
  { id: "wealth", label: "재물·투자 리스크", emoji: "💰" },
  { id: "career", label: "커리어 전환 타이밍", emoji: "💼" },
  { id: "love", label: "연애·결혼 시기", emoji: "❤️" },
  { id: "warning", label: "피해야 할 것", emoji: "⚠️" },
  { id: "year", label: "올해 운세", emoji: "📅" },
];

const AI_ORB_STYLE = { background: "linear-gradient(135deg,#7C5CFF,#A86BF0)" };

const cleanText = (text) => text
  .replace(/#{1,3}\s*/g, "")
  .replace(/\*\*(.*?)\*\*/g, "$1")
  .replace(/\*(.*?)\*/g, "$1")
  .trim();

const splitParagraphs = (text) => cleanText(text || "")
  .split(/\n{2,}/)
  .map((p) => p.trim())
  .filter((p) => p.length > 0);

function findDaeunValue(obj, keys) {
  if (!obj || typeof obj !== "object") return "";
  for (const key of keys) if (obj[key]) return obj[key];
  for (const value of Object.values(obj)) {
    const found = findDaeunValue(value, keys);
    if (found) return found;
  }
  return "";
}

function activeSpecialSalNames(orrerySpecialSals, fallbackActive) {
  const labels = {
    dohwa: "도화살",
    hongyeom: "홍염살",
    gwimun: "귀문관살",
    wonjin: "원진살",
    hwagae: "화개살",
    yeokma: "역마살",
    baekho: "백호살",
    goegang: "괴강살",
    yangin: "양인살",
    cheonul: "천을귀인",
    cheonduk: "천덕귀인",
    wolduk: "월덕귀인",
    munchang: "문창귀인",
    geumyeo: "금여귀인",
  };

  const names = new Set();
  const addName = (item, keyHint) => {
    if (!item) return;
    if (typeof item === "string") names.add(labels[item] || item);
    else if (typeof item === "object") {
      const key = item.key || item.id || keyHint;
      const active = item.active !== false;
      if (active) names.add(item.name || item.label || labels[key] || key);
    }
  };

  if (Array.isArray(orrerySpecialSals)) {
    orrerySpecialSals.forEach((item) => addName(item));
  } else if (orrerySpecialSals && typeof orrerySpecialSals === "object") {
    Object.entries(orrerySpecialSals).forEach(([key, value]) => {
      if (value === true) names.add(labels[key] || key);
      else if (Array.isArray(value) && value.length) names.add(labels[key] || key);
      else if (value && typeof value === "object") addName(value, key);
    });
  }

  (fallbackActive || []).forEach((item) => addName(item));
  return [...names];
}

function buildAnalysisContext(profile) {
  if (!profile) return null;

  const saju = window.computeSaju(profile);
  const reportData = saju.freeReport?.data || {};
  const currentAge = new Date().getFullYear() - profile.y;
  const thisYear = new Date().getFullYear();
  const stems = ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"];
  const branches = ["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"];
  const stemIdx = (thisYear - 4) % 10;
  const branchIdx = (thisYear - 4) % 12;
  const yearGanzi = stems[stemIdx] + branches[branchIdx];
  console.log("올해 세운:", yearGanzi);
  const daeunList = reportData.daeun?.list || [];
  const currentDaeunIndex = daeunList.findIndex((d) => d.ageStart <= currentAge && currentAge <= d.ageEnd);
  const currentDaeun = currentDaeunIndex >= 0 ? daeunList[currentDaeunIndex] : null;
  const currentOrreryDaeun = currentDaeunIndex >= 0 ? reportData.orreryDaewoon?.[currentDaeunIndex] : null;
  const elementStats = reportData.elementStats || { strong: [], weak: [] };
  const dayMaster = saju.dayMaster || {};
  const daeunTenStar = findDaeunValue(currentOrreryDaeun, ["stemSipsin", "stemTenStar", "tenStar", "sipsin", "sibsin", "십신"]) || "십신 미상";
  const daeunStage = findDaeunValue(currentOrreryDaeun, ["unseong", "twelveStage", "twelveFortune", "운성", "12운성"]) || "운성 미상";

  return {
    saju,
    summary: {
      name: profile.name || "고객",
      currentAge,
      currentDaeun: currentDaeun?.gapja || "대운 미상",
      daeunTenStar,
      daeunStage,
      dayMasterLabel: `${dayMaster.k || ""}${dayMaster.el || ""}` || dayMaster.h || "일간 미상",
    },
    api: {
      name: profile.name || "고객",
      dayMaster: `${dayMaster.k || ""}${dayMaster.el || ""}` || dayMaster.h || "일간 미상",
      element: saju.element || dayMaster.el || "",
      yinYang: saju.yinYang?.startsWith("음") ? "음" : "양",
      currentAge,
      currentDaeun: currentDaeun?.gapja || "대운 미상",
      daeunTenStar,
      daeunStage,
      strongElements: (elementStats.strong || []).join(", ") || "없음",
      weakElements: (elementStats.weak || []).join(", ") || "없음",
      yearGanzi,
      specialSals: activeSpecialSalNames(reportData.orrerySpecialSals, reportData.shinsal?.active),
      isGongmang: !!reportData.orreryGongmang,
    },
  };
}

function AnalysisScreen({ nav, profile, addDiary, diaryItem }) {
  const [step, setStep] = window.useStore("wolha_analysis_step", "topic");
  const [selectedTopicId, setSelectedTopicId] = window.useStore("wolha_analysis_selected_topic_id", "");
  const [impUid, setImpUid] = window.useStore("wolha_analysis_imp_uid", "");
  const [result, setResult] = window.useStore("wolha_analysis_result", "");
  const [followUpResult, setFollowUpResult] = window.useStore("wolha_analysis_followup_result", "");
  const [followUpCount, setFollowUpCount] = window.useStore("wolha_analysis_followup_count", 0);
  const [followUpInput, setFollowUpInput] = window.useStore("wolha_analysis_followup_input", "");
  const [followUpQuestion, setFollowUpQuestion] = window.useStore("wolha_analysis_followup_question", "");
  const [loading, setLoading] = anS(false);
  const [followUpLoading, setFollowUpLoading] = anS(false);
  const [error, setError] = anS("");

  const context = anM(() => buildAnalysisContext(profile), [profile]);
  const selectedTopic = ANALYSIS_TOPICS.find((topic) => topic.id === selectedTopicId);

  anE(() => {
    if (!diaryItem || diaryItem.kind !== "analysis") return;
    const topic = ANALYSIS_TOPICS.find((item) =>
      item.id === diaryItem.topicId ||
      item.label === diaryItem.topicLabel ||
      item.emoji === diaryItem.topicEmoji ||
      item.emoji === diaryItem.glyph
    );

    setStep("result");
    setSelectedTopicId(topic?.id || diaryItem.topicId || selectedTopicId);
    setImpUid(diaryItem.id || "");
    setResult(diaryItem.fullResult || diaryItem.result || diaryItem.preview || "");
    setFollowUpResult("");
    setFollowUpCount(0);
    setFollowUpInput("");
    setFollowUpQuestion("");
    setLoading(false);
    setFollowUpLoading(false);
    setError("");
  }, [diaryItem?.id]);

  const resetForTopic = () => {
    setStep("topic");
    setSelectedTopicId("");
    setImpUid("");
    setResult("");
    setFollowUpResult("");
    setFollowUpCount(0);
    setFollowUpInput("");
    setFollowUpQuestion("");
    setLoading(false);
    setFollowUpLoading(false);
    setError("");
  };


  const handleFollowUp = async () => {
    const question = followUpInput.trim();
    if (!question || followUpLoading) return;
    setFollowUpQuestion(question);
    setFollowUpInput("");
    setFollowUpLoading(true);
    setFollowUpResult("");
    try {
      const res = await fetch(`${API_BASE}/api/followup`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          impUid,
          followUpCount: followUpCount + 1,
          question,
          previousResult: result,
          sajuContext: context.api,
        }),
      });
      if (!res.ok) throw new Error(res.status);
      const data = await res.json();
      setFollowUpResult(data.result || "");
      setFollowUpCount((c) => c + 1);
    } catch (e) {
      setFollowUpResult("답변 중 오류가 발생했어요. 잠시 후 다시 시도해 주세요.");
    } finally {
      setFollowUpLoading(false);
    }
  };

  const requestAnalyze = async () => {
    if (!impUid || !selectedTopic || !context) return;
    setLoading(true);
    setResult("");
    setError("");
    try {
      const res = await fetch(`${API_BASE}/api/analyze`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          impUid,
          topic: selectedTopic.id,
          sajuContext: context.api,
        }),
      });

      if (res.status === 403) throw new Error("payment_verification_failed");
      if (!res.ok) throw new Error(res.status);

      const data = await res.json();
      const resultText = data.result || "";
      setResult(resultText);
      addDiary?.({
        id: impUid,
        kind: "analysis",
        title: `${profile.name}님의 ${selectedTopic.label} 분석`,
        preview: resultText.length > 38 ? resultText.slice(0, 38) + "…" : resultText,
        fullResult: resultText,
        result: resultText,
        topicId: selectedTopic.id,
        topicLabel: selectedTopic.label,
        topicEmoji: selectedTopic?.emoji || "命",
        glyph: selectedTopic?.emoji || "命",
        color: "linear-gradient(135deg,#7C5CFF,#A86BF0)",
        when: "방금",
      });
    } catch (e) {
      setError(e.message === "payment_verification_failed" ? "결제 확인에 실패했어요." : "분석 중 오류가 발생했어요. 잠시 후 다시 시도해 주세요.");
    } finally {
      setLoading(false);
    }
  };

  anE(() => {
    if (step === "result" && impUid && selectedTopic && !result && !loading && !error) {
      requestAnalyze();
    }
  }, [step, impUid, selectedTopicId]);

  anE(() => {
    if (step === "result") {
      window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });
    }
  }, [followUpResult, followUpLoading]);

  if (step === "result") {
    const paragraphs = splitParagraphs(result);
    const followUpParagraphs = splitParagraphs(followUpResult);
    const canShowComposer = !loading && !followUpLoading && !!result && followUpCount < 2;

    if (loading) {
      return (
        <window.LoadingScreen variant="orbit" steps={[
          { msg: "사주 데이터를 불러오는 중", sub: "원국 분석 준비" },
          { msg: "명리학 데이터를 대조하는 중", sub: "십신·12운성·신살" },
          { msg: "AI가 당신의 흐름을 읽는 중", sub: "DeepSeek 분석 중" },
          { msg: "심층 리포트를 완성하는 중", sub: "거의 다 왔어요" },
        ]} />
      );
    }

    return (
      <div className="page">
        <div className="chat-head">
          <button className="icon-btn" onClick={() => setStep("topic")}>
            <window.Icon name="back" />
          </button>
          <div className="ch-orb" style={AI_ORB_STYLE}>命</div>
          <div className="ch-txt">
            <b>명리학자 도현</b>
            <span>{selectedTopic?.emoji} {selectedTopic?.label}</span>
          </div>
        </div>

        <div className="msgs">
          <div className="msg ai">
            <div className="m-orb" style={AI_ORB_STYLE}>命</div>
            <div className="bubble">
              {selectedTopic?.emoji} {profile.name}님의 {selectedTopic?.label} 분석을 시작할게요.
            </div>
          </div>

          {loading && (
            <div className="msg ai">
              <div className="m-orb" style={AI_ORB_STYLE}>命</div>
              <div className="bubble"><window.Typing /></div>
            </div>
          )}

          {!loading && error && (
            <div className="msg ai">
              <div className="m-orb" style={AI_ORB_STYLE}>命</div>
              <div className="bubble">{error}</div>
            </div>
          )}

          {!loading && !error && paragraphs.map((paragraph, index) => (
            <div key={index} className="msg ai">
              <div className="m-orb" style={AI_ORB_STYLE}>命</div>
              <div className="bubble" style={{ lineHeight: 1.75, wordBreak: "keep-all" }}>{paragraph}</div>
            </div>
          ))}

          {followUpQuestion && (
            <div className="msg me">
              <div className="m-orb">{profile.name?.[0] || "나"}</div>
              <div className="bubble">{followUpQuestion}</div>
            </div>
          )}

          {followUpLoading && (
            <div className="msg ai">
              <div className="m-orb" style={AI_ORB_STYLE}>命</div>
              <div className="bubble"><window.Typing /></div>
            </div>
          )}

          {!followUpLoading && followUpParagraphs.map((paragraph, index) => (
            <div key={index} className="msg ai">
              <div className="m-orb" style={AI_ORB_STYLE}>命</div>
              <div className="bubble" style={{ lineHeight: 1.75, wordBreak: "keep-all" }}>{paragraph}</div>
            </div>
          ))}

          {!loading && !followUpLoading && result && followUpCount >= 2 && (
            <div className="msg ai">
              <div className="m-orb" style={AI_ORB_STYLE}>命</div>
              <div className="bubble">추가 질문을 모두 사용했어요. 다른 주제가 궁금하다면 아래 버튼을 눌러보세요.</div>
            </div>
          )}
        </div>

        {canShowComposer && (
          <div className="composer">
            <textarea
              rows="1"
              value={followUpInput}
              onChange={(e) => setFollowUpInput(e.target.value)}
              placeholder={(2 - followUpCount) + "번 더 질문할 수 있어요…"}
            />
            <button
              className="send-btn"
              disabled={!followUpInput.trim() || followUpLoading}
              onClick={handleFollowUp}
            >
              <window.Icon name="send" />
            </button>
          </div>
        )}

        {!loading && !followUpLoading && result && (
          <div className="stack">
            <button className="btn ghost" onClick={resetForTopic}>다른 주제 분석하기</button>
            <button className="btn" onClick={() => nav("home")}>홈으로</button>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="page">
      <div className="page-head rise">
        <span className="eyebrow">PREMIUM · SAJU</span>
        <h1>심층분석</h1>
        <p>{context.summary.name}님 · 일간 {context.summary.dayMasterLabel} · 현재 {context.summary.currentAge}세 {context.summary.currentDaeun} 대운({context.summary.daeunTenStar}·{context.summary.daeunStage})</p>
      </div>

      <div className="card panel rise">
        <h3>분석 주제 선택</h3>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: 10 }}>
          {ANALYSIS_TOPICS.map((topic) => {
            const selected = selectedTopicId === topic.id;
            return (
              <button
                key={topic.id}
                type="button"
                onClick={() => setSelectedTopicId(topic.id)}
                style={{
                  minHeight: 86,
                  border: selected ? "1.8px solid var(--primary)" : "1.4px solid var(--line-2)",
                  borderRadius: 20,
                  padding: "14px 10px",
                  background: selected ? "#F1ECFA" : "var(--surface)",
                  color: selected ? "var(--primary)" : "var(--text)",
                  font: "inherit",
                  fontWeight: 700,
                  lineHeight: 1.35,
                  boxShadow: selected ? "0 12px 28px rgba(124, 92, 255, .14)" : "none",
                  cursor: "pointer",
                }}
              >
                {topic.emoji} {topic.label}
              </button>
            );
          })}
        </div>
      </div>

      {error && <div className="card panel body-txt" style={{ color: "var(--danger, #D94A4A)" }}>{error}</div>}

      <div style={{ width: "100%", display: "flex", justifyContent: "center" }}>
        <button className="btn" style={{ width: "100%" }} disabled={!selectedTopicId} onClick={() => {
          const testImpUid = "test_" + Date.now();
          setImpUid(testImpUid);
          setStep("result");
        }}>분석 시작하기 · 4,900원</button>
      </div>
    </div>
  );
}

Object.assign(window, { AnalysisScreen });
