"use client";

import Link from "next/link";
import { useLayoutEffect, useRef, useState, type ElementType, type FocusEvent, type KeyboardEvent } from "react";
import type { ProductPublic } from "@/lib/products";
import type { LandingConfig, LandingFaqItem, LandingModule, LandingTextBlock } from "@/lib/landing-default";
import { blockWrapStyle, moneyBrl, newLandingId } from "@/lib/landing-default";
import { normalizeHeadlineValue } from "@/lib/headline-format";
import { assetDisplayUrl } from "@/lib/asset-url";
import LandingBanner from "./LandingBanner";
import BlockStyleBar from "./BlockStyleBar";
import HeadlineEditable from "./HeadlineEditable";

type Props = {
  product: ProductPublic;
  domain: string;
  editing?: boolean;
  onLandingChange?: (landing: LandingConfig) => void;
  checkoutHref?: string;
};


function cleanEditableField(key: keyof LandingConfig, raw: string): string {
  let v = raw.trim();
  if (key === "headline") v = normalizeHeadlineValue(v);
  if (key === "priceFrom") v = v.replace(/^De\s*R\$\s*/i, "");
  if (key === "guarantee") v = v.replace(/^🛡\s*/, "");
  return v;
}

function EditableBlock({
  tag: Tag,
  field,
  value,
  editing,
  className,
  display,
  onPatch,
}: {
  tag: ElementType;
  field: keyof LandingConfig;
  value: string;
  editing?: boolean;
  className?: string;
  display?: string;
  onPatch?: (patch: Partial<LandingConfig>) => void;
}) {
  const ref = useRef<HTMLElement>(null);
  const [isFocused, setIsFocused] = useState(false);
  const shown = display ?? value;
  const editText = shown;
  const preview = shown;

  useLayoutEffect(() => {
    if (!isFocused || !ref.current) return;
    const el = ref.current;
    el.textContent = editText;
    el.focus();
    const range = document.createRange();
    const sel = window.getSelection();
    range.selectNodeContents(el);
    range.collapse(false);
    sel?.removeAllRanges();
    sel?.addRange(range);
  }, [isFocused]); // eslint-disable-line react-hooks/exhaustive-deps -- init ao abrir edição

  const startEdit = () => setIsFocused(true);

  if (!editing) {
    return <Tag className={className}>{preview}</Tag>;
  }

  if (!isFocused) {
    return (
      <Tag
        key="preview"
        className={className}
        onClick={startEdit}
        onKeyDown={(e: KeyboardEvent<HTMLElement>) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            startEdit();
          }
        }}
        role="button"
        tabIndex={0}
        style={{ cursor: "text" }}
        title="Clique para editar"
      >
        {preview}
      </Tag>
    );
  }

  return (
    <Tag
      key="editing"
      ref={ref}
      className={className}
      contentEditable
      suppressContentEditableWarning
      onBlur={(e: FocusEvent<HTMLElement>) => {
        const next = cleanEditableField(field, e.currentTarget.innerText);
        setIsFocused(false);
        onPatch?.({ [field]: next });
      }}
    />
  );
}

export default function LandingView({
  product,
  domain,
  editing = false,
  onLandingChange,
  checkoutHref,
}: Props) {
  const cfg = product.landing;
  const [openFaq, setOpenFaq] = useState<number | null>(null);
  const buyUrl = checkoutHref ?? `/checkout/${product.slug}`;

  const heroBgUrl = cfg.bgImage?.trim() || "";
  const hasHeroImage =
    heroBgUrl.length > 0 && (cfg.bgType === "image" || cfg.bgType === "gradient");
  const heroScale = Math.min(Math.max(cfg.heroVisualScale || 100, 50), 200) / 100;

  const pageBg =
    cfg.bgType === "solid"
      ? cfg.bgSolid
      : cfg.layout === "editorial"
        ? "radial-gradient(1200px 600px at 80% -10%, color-mix(in srgb,var(--accent) 16%,transparent), transparent), #fbf7f0"
        : "radial-gradient(1100px 700px at 75% -5%, color-mix(in srgb,var(--accent) 26%,transparent), transparent), #0a0910";

  const patch = (p: Partial<LandingConfig>) => onLandingChange?.({ ...cfg, ...p });

  const updateModule = (index: number, m: Partial<LandingModule>) => {
    const modules = cfg.modules.map((item, i) => (i === index ? { ...item, ...m } : item));
    patch({ modules });
  };

  const removeModule = (index: number) => {
    patch({ modules: cfg.modules.filter((_, i) => i !== index) });
  };

  const addModule = () => {
    patch({
      modules: [
        ...cfg.modules,
        { title: "Novo capítulo", subtitle: "Descrição do capítulo", page: "00" },
      ],
    });
  };

  const updateFaq = (id: string, f: Partial<LandingFaqItem>) => {
    patch({ faqs: cfg.faqs.map((item) => (item.id === id ? { ...item, ...f } : item)) });
  };

  const removeFaq = (id: string) => {
    patch({ faqs: cfg.faqs.filter((f) => f.id !== id) });
  };

  const addFaq = () => {
    patch({
      faqs: [
        ...cfg.faqs,
        { id: newLandingId(), question: "Nova pergunta", answer: "Resposta aqui." },
      ],
    });
  };

  const updateTextBlock = (id: string, b: Partial<LandingTextBlock>) => {
    patch({
      textBlocks: cfg.textBlocks.map((item) => (item.id === id ? { ...item, ...b } : item)),
    });
  };

  const removeTextBlock = (id: string) => {
    patch({ textBlocks: cfg.textBlocks.filter((b) => b.id !== id) });
  };

  const addTextBlock = () => {
    patch({
      textBlocks: [
        ...cfg.textBlocks,
        {
          id: newLandingId(),
          title: "Título da seção",
          body: "Escreva uma descrição extra para convencer o visitante.",
          style: { align: "left", maxWidth: 720 },
        },
      ],
    });
  };

  const updateMetric = (id: string, value: string, label: string) => {
    patch({
      metrics: cfg.metrics.map((m) => (m.id === id ? { ...m, value, label } : m)),
    });
  };

  const BuyBtn = ({ className = "lpbtn buy", children }: { className?: string; children: React.ReactNode }) =>
    editing ? (
      <button type="button" className={className}>
        {children}
      </button>
    ) : (
      <Link href={buyUrl} className={className}>
        {children}
      </Link>
    );

  return (
    <div
      className={`lp${cfg.layout === "editorial" ? " light" : ""}${hasHeroImage ? " has-hero-bg" : ""}${editing ? " editing" : ""}`}
      style={
        {
          ["--accent" as string]: cfg.accent,
          ["--accent2" as string]: cfg.accent2,
          background: pageBg,
        } as React.CSSProperties
      }
    >
      <LandingBanner cfg={cfg} />

      <section className="hero">
        {hasHeroImage && (
          <div className="hero-bg" aria-hidden>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={assetDisplayUrl(heroBgUrl)}
              alt=""
              loading="eager"
              decoding="async"
            />
            <div className="hero-bg-shade" />
          </div>
        )}
        <div className="glow g1" />
        <div className="glow g2" />
        <div className="w">
          <div className="grid">
            <div>
              <span className="eyebrow">
                <span className="dot" />
                <EditableBlock
                  tag="span"
                  field="eyebrow"
                  value={cfg.eyebrow}
                  editing={editing}
                  onPatch={patch}
                />
              </span>
              <HeadlineEditable
                value={cfg.headline}
                editing={editing}
                className="hl"
                onPatch={patch}
              />
              <EditableBlock
                tag="p"
                field="sub"
                value={cfg.sub}
                editing={editing}
                className="sub"
                onPatch={patch}
              />
              <div className="cta-row">
                <BuyBtn>
                  <EditableBlock tag="span" field="cta" value={cfg.cta} editing={editing} onPatch={patch} />
                  <span className="arr">→</span>
                </BuyBtn>
                <span className="meta">
                  {moneyBrl(cfg.price)} • e-book PDF
                </span>
              </div>
              <div className="trust">
                <span className="stars">★★★★★</span>
                <small>Guia completo • {cfg.modules.length} capítulos</small>
              </div>
            </div>
            {cfg.heroVisualUrl?.trim() ? (
              <div
                className="hero-visual-img"
                style={{ ["--hero-scale" as string]: String(heroScale) }}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={assetDisplayUrl(cfg.heroVisualUrl)}
                  alt=""
                  loading="eager"
                />
              </div>
            ) : null}
          </div>
        </div>
      </section>

      <section className="strip">
        <div className="w">
          <div className="metrics">
            {cfg.metrics.map((m, i) => (
              <div key={m.id}>
                <div
                  className="n"
                  contentEditable={editing}
                  suppressContentEditableWarning={editing}
                  onBlur={
                    editing
                      ? (e) => {
                          const val = e.currentTarget.innerText.trim();
                          const auto = i === 0 ? String(cfg.modules.length) : val;
                          updateMetric(m.id, i === 0 ? auto : val, m.label);
                        }
                      : undefined
                  }
                >
                  {i === 0 ? cfg.modules.length : m.value}
                </div>
                <div
                  className="l"
                  contentEditable={editing}
                  suppressContentEditableWarning={editing}
                  onBlur={
                    editing
                      ? (e) => updateMetric(m.id, i === 0 ? String(cfg.modules.length) : m.value, e.currentTarget.innerText.trim())
                      : undefined
                  }
                >
                  {m.label}
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="w" style={blockWrapStyle(cfg.summaryStyle)}>
          {editing ? (
            <BlockStyleBar
              style={cfg.summaryStyle}
              onChange={(summaryStyle) => patch({ summaryStyle })}
            />
          ) : null}
          <EditableBlock
            tag="div"
            field="summaryKick"
            value={cfg.summaryKick}
            editing={editing}
            className="kick"
            onPatch={patch}
          />
          <EditableBlock
            tag="h2"
            field="summaryTitle"
            value={cfg.summaryTitle}
            editing={editing}
            className="h2"
            onPatch={patch}
          />
          <EditableBlock
            tag="p"
            field="summaryLead"
            value={cfg.summaryLead}
            editing={editing}
            className="lead"
            onPatch={patch}
          />
          <div className="mods">
            {cfg.modules.map((m, i) => (
              <div className={`mod${editing ? " mod-editing" : ""}`} key={`${m.title}-${i}`}>
                {editing ? (
                  <button type="button" className="canvas-rm" onClick={() => removeModule(i)} title="Remover">
                    ×
                  </button>
                ) : null}
                <div className="ck">✓</div>
                <div className="mod-body">
                  <b
                    contentEditable={editing}
                    suppressContentEditableWarning={editing}
                    onBlur={editing ? (e) => updateModule(i, { title: e.currentTarget.innerText.trim() }) : undefined}
                  >
                    {m.title}
                  </b>
                  <span
                    contentEditable={editing}
                    suppressContentEditableWarning={editing}
                    onBlur={editing ? (e) => updateModule(i, { subtitle: e.currentTarget.innerText.trim() }) : undefined}
                  >
                    {m.subtitle}
                  </span>
                </div>
                <span
                  className="pg"
                  contentEditable={editing}
                  suppressContentEditableWarning={editing}
                  onBlur={editing ? (e) => updateModule(i, { page: e.currentTarget.innerText.trim() }) : undefined}
                >
                  {m.page}
                </span>
              </div>
            ))}
          </div>
          {editing ? (
            <button type="button" className="canvas-add" onClick={addModule}>
              + Adicionar capítulo
            </button>
          ) : null}
        </div>
      </section>

      {cfg.textBlocks.map((block) => (
        <section className="section" key={block.id}>
          <div className="w" style={blockWrapStyle(block.style)}>
            {editing ? (
              <>
                <BlockStyleBar
                  style={block.style}
                  onChange={(style) => updateTextBlock(block.id, { style })}
                />
                <button type="button" className="canvas-rm canvas-rm-block" onClick={() => removeTextBlock(block.id)}>
                  × Remover seção
                </button>
              </>
            ) : null}
            <h2
              className="h2"
              contentEditable={editing}
              suppressContentEditableWarning={editing}
              onBlur={editing ? (e) => updateTextBlock(block.id, { title: e.currentTarget.innerText.trim() }) : undefined}
            >
              {block.title}
            </h2>
            <p
              className="lead"
              contentEditable={editing}
              suppressContentEditableWarning={editing}
              onBlur={editing ? (e) => updateTextBlock(block.id, { body: e.currentTarget.innerText.trim() }) : undefined}
            >
              {block.body}
            </p>
          </div>
        </section>
      ))}

      {editing ? (
        <section className="section">
          <div className="w">
            <button type="button" className="canvas-add" onClick={addTextBlock}>
              + Adicionar bloco de descrição
            </button>
          </div>
        </section>
      ) : null}

      <section className="offer">
        <div className="w">
          <div className="price-card">
            <EditableBlock
              tag="span"
              field="badge"
              value={cfg.badge}
              editing={editing}
              className="badge"
              onPatch={patch}
            />
            <EditableBlock
              tag="div"
              field="priceFrom"
              value={cfg.priceFrom}
              display={`De R$ ${cfg.priceFrom}`}
              editing={editing}
              className="from"
              onPatch={patch}
            />
            <div className="now">
              <span className="cur">R$</span>
              <EditableBlock
                tag="span"
                field="price"
                value={cfg.price}
                editing={editing}
                className="val"
                onPatch={patch}
              />
            </div>
            <EditableBlock
              tag="div"
              field="installments"
              value={cfg.installments}
              editing={editing}
              className="inst"
              onPatch={patch}
            />
            <BuyBtn className="lpbtn buy">
              <span>{cfg.cta}</span>
              <span className="arr">→</span>
            </BuyBtn>
            <EditableBlock
              tag="div"
              field="guarantee"
              value={cfg.guarantee}
              display={`🛡 ${cfg.guarantee}`}
              editing={editing}
              className="grnt"
              onPatch={patch}
            />
            <div className="secure">
              <span>🔒 Pagamento seguro</span>
              <span>⚡ Acesso imediato</span>
              <span>💳 Pix ou cartão</span>
            </div>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="w" style={blockWrapStyle(cfg.faqStyle)}>
          {editing ? (
            <BlockStyleBar style={cfg.faqStyle} onChange={(faqStyle) => patch({ faqStyle })} />
          ) : null}
          <EditableBlock
            tag="div"
            field="faqKick"
            value={cfg.faqKick}
            editing={editing}
            className="kick"
            onPatch={patch}
          />
          <EditableBlock
            tag="h2"
            field="faqTitle"
            value={cfg.faqTitle}
            editing={editing}
            className="h2"
            onPatch={patch}
          />
          <div className="faq">
            {cfg.faqs.map((f, i) => (
              <div className={`q${openFaq === i ? " open" : ""}${editing ? " q-editing" : ""}`} key={f.id}>
                {editing ? (
                  <button type="button" className="canvas-rm canvas-rm-faq" onClick={() => removeFaq(f.id)}>
                    ×
                  </button>
                ) : null}
                <button
                  type="button"
                  onClick={() => !editing && setOpenFaq(openFaq === i ? null : i)}
                  className="faq-q-btn"
                >
                  <span
                    contentEditable={editing}
                    suppressContentEditableWarning={editing}
                    onBlur={editing ? (e) => updateFaq(f.id, { question: e.currentTarget.innerText.trim() }) : undefined}
                  >
                    {f.question}
                  </span>
                  {!editing ? <span className="pm">+</span> : null}
                </button>
                <div
                  className="a"
                  contentEditable={editing}
                  suppressContentEditableWarning={editing}
                  onBlur={editing ? (e) => updateFaq(f.id, { answer: e.currentTarget.innerText.trim() }) : undefined}
                >
                  {f.answer}
                </div>
              </div>
            ))}
          </div>
          {editing ? (
            <button type="button" className="canvas-add" onClick={addFaq}>
              + Adicionar pergunta
            </button>
          ) : null}
        </div>
      </section>

      <footer className="lpfoot">
        <div className="w">
          <b>{product.name}</b> — {domain}/{product.slug}
          <br />© {new Date().getFullYear()} landpage.agenciajob.com
        </div>
      </footer>
    </div>
  );
}
