"use client";

import { ACCENT_PRESETS, type LandingConfig } from "@/lib/landing-default";
import { formatHeadline, normalizeHeadlineValue } from "@/lib/headline-format";
import type { ProductPublic } from "@/lib/products";
import ImageUploadField from "./ImageUploadField";
import ProductContentManager from "./ProductContentManager";
import ProductOffersEditor from "./ProductOffersEditor";

type Props = {
  open: boolean;
  landing: LandingConfig;
  productSlug: string;
  allProducts: ProductPublic[];
  onChange: (landing: LandingConfig) => void;
  onClose: () => void;
  onSave: () => void;
  onReset: () => void;
  saving?: boolean;
};

export default function LandingEditor({
  open,
  landing,
  productSlug,
  allProducts,
  onChange,
  onClose,
  onSave,
  onReset,
  saving = false,
}: Props) {
  const set = (patch: Partial<LandingConfig>) => onChange({ ...landing, ...patch });

  return (
    <aside id="lped" className={open ? "open" : ""}>
      <div className="h">
        <b>Editor</b>
        <button type="button" className="x" onClick={onClose}>
          ×
        </button>
      </div>
      <div className="body">
        {/* 1 — Banner */}
        <div className="grp">
          <label>1. Banner no topo</label>
          <p style={{ fontSize: ".78rem", color: "rgba(255,255,255,.5)", marginBottom: 10 }}>
            Faixa acima de toda a página (imagem ou vídeo).
          </p>
          <div className="bgt">
            {(["none", "image", "video"] as const).map((b) => (
              <button
                key={b}
                type="button"
                className={landing.bannerType === b ? "active" : ""}
                onClick={() => set({ bannerType: b, bannerUrl: b === "none" ? "" : landing.bannerUrl })}
              >
                {b === "none" ? "Nenhum" : b === "image" ? "Imagem" : "Vídeo"}
              </button>
            ))}
          </div>
          {landing.bannerType === "image" && (
            <div className="f" style={{ marginTop: 10 }}>
              <ImageUploadField
                url={landing.bannerUrl}
                onUrl={(bannerUrl) => set({ bannerUrl, bannerType: "image" })}
                previewHeight={64}
              />
            </div>
          )}
          {landing.bannerType === "video" && (
            <div className="f" style={{ marginTop: 10 }}>
              <span>URL do vídeo (MP4 ou embed)</span>
              <input
                value={landing.bannerUrl}
                onChange={(e) => set({ bannerUrl: e.target.value })}
                placeholder="https://...video.mp4"
              />
            </div>
          )}
        </div>

        {/* 2 — Fundo hero */}
        <div className="grp">
          <label>2. Fundo da seção principal</label>
          <p style={{ fontSize: ".78rem", color: "rgba(255,255,255,.5)", marginBottom: 10 }}>
            Imagem atrás do título e da imagem lateral.
          </p>
          <div className="bgt">
            {(["gradient", "solid", "image"] as const).map((b) => (
              <button
                key={b}
                type="button"
                className={landing.bgType === b ? "active" : ""}
                onClick={() => set({ bgType: b })}
              >
                {b === "gradient" ? "Gradiente" : b === "solid" ? "Sólido" : "Imagem"}
              </button>
            ))}
          </div>
          {landing.bgType === "image" && (
            <div className="f" style={{ marginTop: 10 }}>
              <ImageUploadField
                url={landing.bgImage}
                onUrl={(bgImage) => set({ bgImage, bgType: "image" })}
                previewHeight={80}
              />
            </div>
          )}
          {landing.bgType === "solid" && (
            <div className="f" style={{ marginTop: 10 }}>
              <span>Cor sólida</span>
              <div className="crow">
                <input
                  type="color"
                  value={landing.bgSolid}
                  onChange={(e) => set({ bgSolid: e.target.value })}
                />
              </div>
            </div>
          )}
        </div>

        {/* 3 — Imagem lateral direita */}
        <div className="grp">
          <label>3. Imagem ao lado do título (direita)</label>
          <p style={{ fontSize: ".78rem", color: "rgba(255,255,255,.5)", marginBottom: 10 }}>
            Capa do produto ou foto — à direita do título (tamanho 50–200%).
          </p>
          <ImageUploadField
            url={landing.heroVisualUrl}
            onUrl={(heroVisualUrl) => set({ heroVisualUrl, heroVisual: "image" })}
            scale={landing.heroVisualScale ?? 100}
            onScale={(heroVisualScale) => set({ heroVisualScale })}
            showScale
            previewHeight={120}
          />
        </div>

        <div className="grp">
          <label>4. Conteúdos do produto</label>
          <p style={{ fontSize: ".78rem", color: "rgba(255,255,255,.5)", marginBottom: 10 }}>
            Adicione quantos PDFs e vídeos quiser — liberados na biblioteca após o pagamento.
          </p>
          <ProductContentManager productSlug={productSlug} />
        </div>

        <ProductOffersEditor productSlug={productSlug} allProducts={allProducts} />

        <div className="grp">
          <label>Layout</label>
          <div className="lays">
            {(["aurora", "editorial", "premium"] as const).map((l) => (
              <div
                key={l}
                className={`lay${landing.layout === l ? " active" : ""}`}
                onClick={() => set({ layout: l })}
                onKeyDown={() => {}}
                role="button"
                tabIndex={0}
              >
                <div
                  className="sw"
                  style={{
                    background:
                      l === "editorial"
                        ? "linear-gradient(135deg,#fbf7f0,#e7ddcb)"
                        : l === "premium"
                          ? "linear-gradient(135deg,#13111c,#ffb627)"
                          : "linear-gradient(135deg,#ff2e63,#ffb627)",
                  }}
                />
                {l.charAt(0).toUpperCase() + l.slice(1)}
              </div>
            ))}
          </div>
        </div>

        <div className="grp">
          <label>Cor de destaque</label>
          <div className="sws">
            {ACCENT_PRESETS.map(([a, b]) => (
              <div
                key={a}
                className={`swt${landing.accent === a ? " active" : ""}`}
                style={{ background: `linear-gradient(135deg,${a},${b})` }}
                onClick={() => set({ accent: a, accent2: b })}
                role="button"
                tabIndex={0}
              />
            ))}
          </div>
          <div className="crow" style={{ marginTop: 9 }}>
            <input
              type="color"
              value={landing.accent}
              onChange={(e) => set({ accent: e.target.value })}
            />
            <span style={{ fontSize: ".8rem", color: "rgba(255,255,255,.6)" }}>
              Personalizada
            </span>
          </div>
        </div>

        <div className="grp">
          <label>Sumário e FAQ (também na prévia)</label>
          <p style={{ fontSize: ".72rem", color: "rgba(255,255,255,.45)", marginBottom: 10 }}>
            Clique nos textos na página ou use + para capítulos, perguntas e blocos extras.
          </p>
          {(
            [
              ["summaryKick", "Rótulo do sumário"],
              ["summaryTitle", "Título do sumário"],
              ["summaryLead", "Descrição do sumário"],
              ["faqKick", "Rótulo do FAQ"],
              ["faqTitle", "Título do FAQ"],
            ] as const
          ).map(([key, label]) => (
            <div className="f" key={key}>
              <span>{label}</span>
              <input
                value={landing[key]}
                onChange={(e) => set({ [key]: e.target.value })}
              />
            </div>
          ))}
        </div>

        <div className="grp">
          <label>Conteúdo</label>
          {(
            [
              ["eyebrow", "Selo", "input"],
              ["headline", "Título — use *asteriscos* para cor de destaque", "textarea"],
              ["sub", "Subtítulo", "textarea"],
              ["cta", "Texto do botão", "input"],
            ] as const
          ).map(([key, label, kind]) => (
            <div className="f" key={key}>
              <span>{label}</span>
              {kind === "textarea" ? (
                <>
                  <textarea
                    value={landing[key]}
                    onChange={(e) =>
                      set({
                        [key]:
                          key === "headline"
                            ? normalizeHeadlineValue(e.target.value)
                            : e.target.value,
                      })
                    }
                  />
                  {key === "headline" ? (
                    <p
                      className="hl"
                      style={{
                        marginTop: 8,
                        fontSize: "1.05rem",
                        lineHeight: 1.1,
                        fontFamily: "var(--fd)",
                        fontWeight: 800,
                      }}
                      aria-hidden
                    >
                      {formatHeadline(landing.headline)}
                    </p>
                  ) : null}
                </>
              ) : (
                <input
                  value={landing[key]}
                  onChange={(e) => set({ [key]: e.target.value })}
                />
              )}
            </div>
          ))}
        </div>

        <div className="grp">
          <label>Oferta</label>
          {(
            [
              ["badge", "Selo de oferta"],
              ["priceFrom", 'Preço "de" (R$)'],
              ["price", 'Preço "por" (R$)'],
              ["installments", "Parcelamento"],
              ["guarantee", "Garantia"],
            ] as const
          ).map(([key, label]) => (
            <div className="f" key={key}>
              <span>{label}</span>
              <input
                value={landing[key]}
                onChange={(e) => set({ [key]: e.target.value })}
              />
            </div>
          ))}
        </div>
      </div>
      <div className="foot">
        <button type="button" className="reset" onClick={onReset}>
          Restaurar
        </button>
        <button type="button" className="save" onClick={onSave} disabled={saving}>
          {saving ? "Salvando…" : "Salvar"}
        </button>
      </div>
    </aside>
  );
}
