/* global React, MysticHand, SacredGeometry, Wordmark, Icon, Divider */
// ============================================
// QUIROMANTE — Screens
// Hero, Upload, Loading, Paywall, Result
// ============================================

const { useState, useEffect, useRef, useCallback } = React;

// Localhost → local backend; otherwise (ngrok tunnel / prod) → window.QUIROMANTE_API (set in index.html).
const API =
  location.hostname === "localhost" || location.hostname === "127.0.0.1"
    ? "http://localhost:8000"
    : window.QUIROMANTE_API;

// ──────────────────────────────────────────────
// 1. HERO
// ──────────────────────────────────────────────
function HeroScreen({ onStart }) {
  return (
    <section
      className="screen hero-screen"
      data-screen-label="01 Hero"
    >
      <div className="hero-top">
        <Wordmark />
      </div>

      <div className="hero-hand-wrap">
        <MysticHand size={300} />
      </div>

      <div className="hero-text">
        <p className="eyebrow" style={{ marginBottom: 16 }}>
          ✦ Leitura de Quiromancia ✦
        </p>
        <h1 className="display display-xl">
          Sua mão guarda segredos que você ainda não conhece
        </h1>
        <p className="body-lg" style={{ marginTop: 18 }}>
          As linhas da sua mão foram traçadas antes mesmo do seu primeiro suspiro.
          É hora de ouvi-las.
        </p>
      </div>

      <div className="hero-footer">
        <button className="btn btn-primary" onClick={onStart}>
          Revelar minha leitura
          <Icon.ArrowRight />
        </button>

        <div className="hero-meta">
          <span>3.247 leituras realizadas</span>
          <span className="hero-meta-dot" />
          <span>nesta lua crescente</span>
        </div>
      </div>
    </section>
  );
}

// ──────────────────────────────────────────────
// 2. UPLOAD
// ──────────────────────────────────────────────
function UploadScreen({ onBack, onUploadDone, image, setImage }) {
  const fileInputRef = useRef(null);
  const rawFileRef = useRef(null);
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState(null);

  const handleFile = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    rawFileRef.current = file;
    const reader = new FileReader();
    reader.onload = (ev) => setImage(ev.target.result);
    reader.readAsDataURL(file);
  };

  const triggerPick = () => fileInputRef.current?.click();

  const useDemo = () => {
    setImage("demo");
  };

  const handleSubmit = async () => {
    if (image === "demo") {
      onUploadDone(null);
      return;
    }
    if (!rawFileRef.current) return;
    setUploading(true);
    setUploadError(null);
    try {
      const formData = new FormData();
      formData.append("file", rawFileRef.current);
      const res = await fetch(`${API}/api/upload`, { method: "POST", body: formData });
      if (!res.ok) throw new Error(`${res.status}`);
      const data = await res.json();
      onUploadDone(data.session_id);
    } catch (_) {
      setUploadError("Erro ao enviar. Tente novamente.");
      setUploading(false);
    }
  };

  return (
    <section
      className="screen"
      data-screen-label="02 Upload"
    >
      <div className="header-bar">
        <button className="icon-btn" onClick={onBack} aria-label="Voltar">
          <Icon.ArrowLeft />
        </button>
        <Wordmark />
        <div style={{ width: 40 }} />
      </div>

      <div style={{ textAlign: "center", marginBottom: 24 }}>
        <p className="eyebrow" style={{ marginBottom: 12 }}>Passo 1 de 2</p>
        <h2 className="display display-md">
          Fotografe sua mão esquerda aberta, com boa iluminação
        </h2>
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        capture="environment"
        className="hidden-input"
        onChange={handleFile}
      />

      <div
        className={`upload-area ${image ? "has-image" : ""}`}
        onClick={image ? undefined : triggerPick}
        role="button"
        tabIndex={0}
      >
        {image ? (
          <>
            <UploadedPreview image={image} />
            <div className="upload-preview-overlay">
              <button
                className="upload-retake"
                onClick={(e) => { e.stopPropagation(); triggerPick(); }}
              >
                <Icon.Camera width={14} height={14} />
                Refazer foto
              </button>
            </div>
          </>
        ) : (
          <>
            <div className="upload-icon-wrap glow" style={{ color: "var(--gold)" }}>
              <Icon.Camera />
            </div>
            <div style={{ textAlign: "center" }}>
              <p
                className="display"
                style={{ fontSize: 20, marginBottom: 6 }}
              >
                Toque para capturar
              </p>
              <p className="body-sm">
                Câmera ou galeria
              </p>
            </div>
            {/* Decorative palm outline hint */}
            <svg
              viewBox="0 0 120 140"
              width="60"
              style={{ position: "absolute", opacity: 0.05, pointerEvents: "none" }}
            >
              <path
                d="M30 80 C 28 65, 28 50, 30 40 L 36 40 L 38 22 L 46 22 L 46 40 L 54 18 L 62 18 L 62 42 L 70 22 L 78 22 L 78 44 L 86 36 L 92 38 L 86 60 C 84 80, 80 100, 60 110 C 40 118, 28 100, 30 80 Z"
                fill="#C9A84C"
              />
            </svg>
          </>
        )}
      </div>

      <div className="upload-tip">
        <Icon.Sparkle className="upload-tip-icon" />
        <p className="body-sm" style={{ color: "var(--cream-soft)" }}>
          <strong style={{ color: "var(--cream)", fontWeight: 600 }}>
            Use a mão esquerda
          </strong>
          {" "}— ela revela seu destino nato, aquilo que você trouxe ao mundo.
        </p>
      </div>

      <div style={{ flex: 1 }} />

      {uploadError && (
        <p className="caption" style={{ color: "#e07070", textAlign: "center", marginTop: 8 }}>
          {uploadError}
        </p>
      )}

      <button
        className="btn btn-primary"
        onClick={handleSubmit}
        disabled={!image || uploading}
        style={{
          opacity: image && !uploading ? 1 : 0.45,
          pointerEvents: image && !uploading ? "auto" : "none",
          marginTop: 24,
        }}
      >
        {uploading ? "Enviando…" : "Analisar minha mão"}
        {!uploading && <Icon.ArrowRight />}
      </button>

      {!image && (
        <button
          className="btn-ghost"
          onClick={useDemo}
          style={{ alignSelf: "center", marginTop: 8 }}
        >
          Pular — usar demo
        </button>
      )}
    </section>
  );
}

function UploadedPreview({ image }) {
  if (image === "demo") {
    // Stylized SVG of a hand for the demo path
    return (
      <div
        style={{
          position: "absolute",
          inset: 0,
          width: "100%",
          height: "100%",
          background:
            "radial-gradient(ellipse at 50% 45%, #3D2F22 0%, #1A1208 70%, #0A0604 100%)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <MysticHand size={240} animated={false} />
      </div>
    );
  }
  return <img src={image} alt="Sua mão" className="upload-preview" />;
}

// ──────────────────────────────────────────────
// 3. LOADING
// ──────────────────────────────────────────────
const LOADING_MESSAGES = [
  "Lendo suas linhas da vida…",
  "Interpretando seu mapa emocional…",
  "Decifrando os símbolos do destino…",
  "Conectando com sua energia…",
  "Sua leitura está quase pronta…",
];

const LOADING_TIMEOUT_MS = 45000;
const POLL_INTERVAL_MS = 1500;

function LoadingScreen({ sessionId, onDone, onBack }) {
  const [msgIndex, setMsgIndex] = useState(0);
  const [retryCount, setRetryCount] = useState(0);
  const [loadingError, setLoadingError] = useState(null);
  const onDoneRef = useRef(onDone);
  onDoneRef.current = onDone;

  // Message rotation — always runs independently of API
  useEffect(() => {
    const id = setInterval(() => {
      setMsgIndex((i) => (i + 1) % LOADING_MESSAGES.length);
    }, 2000);
    return () => clearInterval(id);
  }, []);

  // API polling or demo timer
  useEffect(() => {
    setLoadingError(null);

    if (!sessionId) {
      // Demo path: fixed 10s then advance with no reading
      const t = setTimeout(() => onDoneRef.current(null), 10000);
      return () => clearTimeout(t);
    }

    let cancelled = false;
    let pollId = null;
    let timeoutId = null;

    const fail = (message) => {
      if (cancelled) return;
      cancelled = true;
      if (pollId) clearInterval(pollId);
      if (timeoutId) clearTimeout(timeoutId);
      setLoadingError(message);
    };

    (async () => {
      try {
        const generateRes = await fetch(`${API}/api/reading/generate`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ session_id: sessionId }),
        });
        if (!generateRes.ok) {
          throw new Error(`Generate failed with status ${generateRes.status}`);
        }
      } catch (_) {
        fail("Não consegui abrir esta leitura agora. Tente novamente em instantes.");
        return;
      }

      timeoutId = setTimeout(() => {
        fail("As linhas demoraram mais do que o esperado. Tente novamente.");
      }, LOADING_TIMEOUT_MS);

      pollId = setInterval(async () => {
        if (cancelled) { clearInterval(pollId); return; }
        try {
          const res = await fetch(`${API}/api/reading/${sessionId}`);
          if (!res.ok) {
            throw new Error(`Polling failed with status ${res.status}`);
          }
          const data = await res.json();
          if (data.status === "complete") {
            clearInterval(pollId);
            clearTimeout(timeoutId);
            if (!cancelled) onDoneRef.current(data.reading ?? null);
          }
          if (data.status === "failed") {
            fail("Não consegui abrir esta leitura agora. Tente novamente em instantes.");
          }
        } catch (_) {
          fail("Perdi a conexão com a leitura. Tente novamente.");
        }
      }, POLL_INTERVAL_MS);
    })();

    return () => {
      cancelled = true;
      if (timeoutId) clearTimeout(timeoutId);
      if (pollId) clearInterval(pollId);
    };
  }, [sessionId, retryCount]);

  if (loadingError) {
    return (
      <section
        className="screen loading-screen"
        data-screen-label="03 Loading"
      >
        <Wordmark />

        <div className="loading-geometry">
          <SacredGeometry size={220} />
        </div>

        <div className="loading-status">
          <p className="eyebrow">Tente novamente</p>
          <p className="loading-message">
            {loadingError}
          </p>
        </div>

        <div className="payment-buttons" style={{ width: "100%", marginBottom: 0 }}>
          <button
            className="btn btn-primary"
            onClick={() => setRetryCount((count) => count + 1)}
          >
            Tentar de novo
          </button>
          <button className="btn btn-secondary" onClick={onBack}>
            Escolher outra foto
          </button>
        </div>
      </section>
    );
  }

  return (
    <section
      className="screen loading-screen"
      data-screen-label="03 Loading"
    >
      <Wordmark />

      <div className="loading-geometry">
        <SacredGeometry size={260} />
      </div>

      <div className="loading-status">
        <p className="eyebrow">Em andamento</p>
        <p className="loading-message" key={msgIndex}>
          {LOADING_MESSAGES[msgIndex]}
        </p>
      </div>

      <div className="loading-progress" />

      <p className="caption" style={{ maxWidth: "28ch", textAlign: "center" }}>
        Não feche este momento. As linhas estão sendo reveladas.
      </p>
    </section>
  );
}

// ──────────────────────────────────────────────
// 4. PAYWALL
// ──────────────────────────────────────────────
const PREVIEW_SECTIONS = [
  { icon: <Icon.Lifeline />, title: "Linha da Vida", hint: "Sua vitalidade e energia vital" },
  { icon: <Icon.Heartline />, title: "Linha do Coração", hint: "Como você ama e é amada" },
  { icon: <Icon.Fate />, title: "Linha do Destino", hint: "Seu propósito e caminho" },
  { icon: <Icon.Gift />, title: "Seu Dom Oculto", hint: "O que sua mão revela só sobre você" },
];

function PaywallScreen({ sessionId, onBack }) {
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  async function startCheckout() {
    if (loading) return;
    setError(null);
    setLoading(true);
    try {
      const res = await fetch(`${API}/api/payment/create-preference`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ session_id: sessionId }),
      });
      if (!res.ok) throw new Error("preference");
      const data = await res.json();
      // sandbox_init_point for test credentials; falls back to init_point.
      window.location.href = data.sandbox_init_point || data.init_point;
    } catch (e) {
      setError("Não foi possível abrir o pagamento. Tente novamente.");
      setLoading(false);
    }
  }

  return (
    <section
      className="screen"
      data-screen-label="04 Paywall"
    >
      <div className="header-bar">
        <button className="icon-btn" onClick={onBack} aria-label="Voltar">
          <Icon.ArrowLeft />
        </button>
        <Wordmark />
        <div style={{ width: 40 }} />
      </div>

      <div className="paywall-header">
        <div className="paywall-checkmark">
          <Icon.Sparkle width={20} height={20} style={{ color: "var(--gold-light)" }} />
        </div>
        <p className="eyebrow" style={{ marginBottom: 10 }}>
          Sua leitura está pronta
        </p>
        <h2 className="display display-lg">
          As linhas falaram. Quer ouvir o que elas dizem sobre você?
        </h2>
      </div>

      <div className="reading-preview">
        <div className="corner-marks" />

        {PREVIEW_SECTIONS.map((s, i) => (
          <div className="preview-section" key={i}>
            <div className="preview-section-icon">{s.icon}</div>
            <div className="preview-section-text">
              <p className="preview-section-title">{s.title}</p>
              <div className="preview-blur-line" style={{ width: "85%" }} />
              <div className="preview-blur-line" style={{ width: "65%" }} />
            </div>
            <div className="preview-section-lock">
              <Icon.Lock />
            </div>
          </div>
        ))}
      </div>

      <div className="price-block">
        <p className="eyebrow">Sua leitura completa</p>
        <p className="price-amount">
          <span className="currency">R$</span>14<span className="cents">,90</span>
        </p>
        <p className="caption" style={{ marginTop: 4, color: "var(--muted-2)" }}>
          pagamento único — sem renovação
        </p>
      </div>

      <div className="payment-buttons">
        <button className="btn btn-primary" onClick={startCheckout} disabled={loading}>
          {loading ? "Abrindo pagamento…" : <><Icon.Sparkle width={18} height={18} /> Desbloquear minha leitura</>}
        </button>
        {error && (
          <p className="caption" style={{ color: "var(--gold-light)", textAlign: "center" }}>
            {error}
          </p>
        )}
      </div>

      <div className="trust-row">
        <div className="trust-item">
          <Icon.ShieldCheck />
          <span>Pagamento 100% seguro e criptografado</span>
        </div>
        <div className="trust-item">
          <Icon.Stars />
          <span>Mais de 3.200 leituras já realizadas</span>
        </div>
      </div>

      <p className="fine-print">
        Acesso imediato após confirmação do pagamento
      </p>
    </section>
  );
}

// ──────────────────────────────────────────────
// 5. RESULT
// ──────────────────────────────────────────────
const READING = [
  {
    eyebrow: "Capítulo Primeiro",
    icon: <Icon.Lifeline />,
    title: "Sua Linha da Vida",
    paragraphs: [
      "Sua linha da vida desce profunda, com um traço firme que se curva generosamente ao redor do monte de Vênus. Isto não fala de quantos anos você viverá — fala da intensidade com que viverá cada um deles.",
      "Há uma pequena bifurcação próxima ao centro: um momento em que você reescreverá quem é. Provavelmente você já o sentiu se aproximando, mesmo sem nome. Seu corpo guarda mais sabedoria do que sua mente admite.",
    ],
  },
  {
    eyebrow: "Capítulo Segundo",
    icon: <Icon.Heartline />,
    title: "Sua Linha do Amor",
    paragraphs: [
      "Sua linha do coração sobe em direção ao indicador, sinal de quem ama com olhos abertos. Você não se entrega por carência — você escolhe. E quando escolhe, escolhe inteira.",
      "Existem pequenas ramificações ascendentes: amores que te ensinaram, não que te quebraram. Cada um deixou uma marca, mas nenhum teve poder sobre quem você é hoje.",
      "Um encontro significativo está marcado nas linhas que cruzam o monte de Júpiter. Pode ser alguém novo — ou alguém que retorna com olhos diferentes.",
    ],
  },
  {
    eyebrow: "Capítulo Terceiro",
    icon: <Icon.Fate />,
    title: "Sua Linha do Destino",
    paragraphs: [
      "Sua linha do destino é interrompida e retomada — isto não é fraqueza, é coragem. Você é daquelas que recomeçam quando o caminho não serve mais, em vez de seguir cumprindo o que não pertence.",
      "Há uma estrela pequena perto da base: um período de reconhecimento se aproxima, em algo que hoje você ainda faz em silêncio. O que parece pequeno agora vai abrir uma porta que você nem sabia existir.",
    ],
  },
  {
    eyebrow: "Capítulo Quarto",
    icon: <Icon.Gift />,
    title: "Seu Dom Oculto",
    paragraphs: [
      "No monte da Lua, sua mão revela algo que muitas não têm: uma sensibilidade que percebe antes de entender. Você sente as pessoas pelo que elas não dizem. Confia no estômago antes da cabeça.",
      "Este dom já te fez parecer estranha em ambientes que não eram seus. Não era estranheza — era frequência diferente. Pare de pedir desculpas por sentir demais. O que parece sensibilidade é, na verdade, precisão.",
    ],
  },
  {
    eyebrow: "Capítulo Final",
    icon: <Icon.Moon />,
    title: "O Que Vem Aí",
    paragraphs: [
      "Três marcas formam um pequeno triângulo no centro da sua palma — uma configuração rara. As próximas luas trazem uma decisão. Você sabe qual é. Sua mão diz: confie.",
      "Há proteção desenhada nas linhas que circundam o polegar. Algo que você herdou de uma mulher da sua família anterior a você cuida do seu caminho. Agradeça quando lembrar.",
    ],
  },
];

const EYEBROWS = [
  "Capítulo Primeiro",
  "Capítulo Segundo",
  "Capítulo Terceiro",
  "Capítulo Quarto",
];

function ResultScreen({ onBack, reading }) {
  const chapters = reading
    ? reading.secoes.map((s, i) => ({
        eyebrow: EYEBROWS[i] || `Capítulo ${i + 1}`,
        icon: <span style={{ fontSize: 22, lineHeight: 1 }}>{s.icone}</span>,
        title: s.titulo,
        paragraphs: s.texto.split(/\n\n+/).filter(Boolean),
      }))
    : READING;

  const handleShare = async () => {
    const text = "Acabei de receber minha leitura de quiromancia ✨";
    if (navigator.share) {
      try {
        await navigator.share({ title: "Quiromante", text });
        return;
      } catch (_) {}
    }
    try {
      await navigator.clipboard.writeText(text);
      alert("Copiado para a área de transferência!");
    } catch (_) {}
  };

  const today = new Date().toLocaleDateString("pt-BR", { day: "numeric", month: "long" });

  return (
    <section
      className="screen"
      data-screen-label="05 Result"
      style={{ paddingTop: 20 }}
    >
      <div className="header-bar" style={{ paddingBottom: 16 }}>
        <button className="icon-btn" onClick={onBack} aria-label="Voltar">
          <Icon.ArrowLeft />
        </button>
        <Wordmark />
        <div style={{ width: 40 }} />
      </div>

      <div className="result-header">
        <p className="eyebrow" style={{ marginBottom: 12 }}>
          ✦ Sua Leitura ✦
        </p>
        {reading?.saudacao && (
          <p
            className="body-lg"
            style={{ fontStyle: "italic", marginBottom: 14, color: "var(--cream-soft)" }}
          >
            {reading.saudacao}
          </p>
        )}
        <h2 className="display display-lg">
          O que suas mãos sussurram
        </h2>
        <p className="body-sm" style={{ marginTop: 12, color: "var(--muted)" }}>
          Lida sob a lua crescente · {today}
        </p>
      </div>

      <Divider />

      {chapters.map((r, i) => (
        <article className="reading-card" key={i}>
          <div className="reading-card-head">
            <div className="reading-card-icon glow">{r.icon}</div>
            <div className="reading-card-titles">
              <p className="reading-card-eyebrow">{r.eyebrow}</p>
              <h3 className="reading-card-title">{r.title}</h3>
            </div>
          </div>
          <div className="reading-card-body">
            {r.paragraphs.map((p, j) => (
              <p key={j}>{p}</p>
            ))}
          </div>
        </article>
      ))}

      {reading?.mensagem_final && (
        <div
          style={{
            padding: "20px 24px",
            textAlign: "center",
            borderTop: "1px solid var(--hairline)",
            marginTop: 8,
          }}
        >
          <p
            className="body-lg"
            style={{ fontStyle: "italic", color: "var(--cream-soft)", lineHeight: 1.7 }}
          >
            {reading.mensagem_final}
          </p>
        </div>
      )}

      <button className="btn share-btn" onClick={handleShare}>
        <Icon.Share />
        Compartilhar minha leitura
      </button>

      <div className="upsell-card">
        <p className="upsell-eyebrow">Quer ir mais fundo?</p>
        <h3 className="upsell-title">
          Uma leitura ao vivo com nossa quiromante
        </h3>
        <p className="upsell-body">
          Conversa privada de 30 minutos no WhatsApp. Ela responde o que sua leitura
          escrita não pôde aprofundar — relacionamentos, escolhas, datas.
        </p>
        <a
          className="btn btn-primary"
          href="https://wa.me/5511999999999?text=Olá!%20Gostaria%20de%20agendar%20uma%20leitura%20ao%20vivo."
          target="_blank"
          rel="noopener noreferrer"
          style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}
        >
          <Icon.WhatsApp />
          Falar com a quiromante
        </a>
      </div>

      <p
        className="caption"
        style={{ textAlign: "center", marginTop: 8, color: "var(--muted-2)" }}
      >
        Quiromante · Leituras autênticas desde 2024
      </p>
    </section>
  );
}

Object.assign(window, {
  HeroScreen,
  UploadScreen,
  LoadingScreen,
  PaywallScreen,
  ResultScreen,
});
