"use client";

import { useState, type CSSProperties, type ReactNode } from "react";
import { resolveMedia, type Content } from "@/app/(admin)/_lib/cms";
import { Icon, type IconName } from "./Icon";

/* ------------------------------------------------------------------ */
/* Helpers                                                             */
/* ------------------------------------------------------------------ */

type O = Record<string, unknown>;
const s = (v: unknown) => (typeof v === "string" ? v : "");
const o = (v: unknown): O => (v && typeof v === "object" && !Array.isArray(v) ? (v as O) : {});
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);

/** Title with its highlighted words in brand blue. */
function Title({ t }: { t: unknown }) {
  const { text, highlight } = o(t) as { text?: string; highlight?: string };
  const tx = s(text);
  const hl = s(highlight).trim();
  const at = hl ? tx.indexOf(hl) : -1;
  if (at < 0) return <>{tx}</>;
  return (
    <>
      {tx.slice(0, at)}
      <span className="hl">{hl}</span>
      {tx.slice(at + hl.length)}
    </>
  );
}

/** Image from the CMS; relative paths need NEXT_PUBLIC_SITE_URL, otherwise a labelled placeholder. */
function Media({ img, className, style, fallbackIcon }: { img: unknown; className?: string; style?: CSSProperties; fallbackIcon?: IconName }) {
  const { url, alt } = o(img);
  const src = resolveMedia(url);
  const [failed, setFailed] = useState<string | null>(null);
  if (!src || failed === src)
    return (
      <div className={`pv-ph ${className ?? ""}`} style={style} title={s(url)}>
        {fallbackIcon ? <Icon name={fallbackIcon} /> : <span>{s(url) || "No image"}</span>}
      </div>
    );
  // eslint-disable-next-line @next/next/no-img-element -- arbitrary external CMS media
  return <img className={className} style={style} src={src} alt={s(alt)} onError={() => setFailed(src)} />;
}

function Ctas({ ctas, dark }: { ctas: unknown; dark?: boolean }) {
  const list = arr(ctas).map(o);
  if (!list.length) return null;
  return (
    <div className="pv-ctas">
      {list.map((c, i) => (
        <span key={i} className={`btn ${i === 0 ? "btn-primary" : dark ? "btn-ghost-dark" : "btn-outline"}`}>
          {s(c.label)}
        </span>
      ))}
    </div>
  );
}

const Body = ({ text, className }: { text: unknown; className?: string }) => (s(text) ? <p className={`pv-body ${className ?? ""}`}>{s(text)}</p> : null);

/* ------------------------------------------------------------------ */
/* Sections                                                            */
/* ------------------------------------------------------------------ */

type Props = { sectionKey: string; type: string; content: Content; selected: boolean; onSelect: () => void; dirty?: boolean };

export function PreviewSection({ sectionKey, type, content: c, selected, onSelect, dirty }: Props) {
  const wrap = (className: string, body: ReactNode, style?: CSSProperties) => (
    <section data-s={sectionKey} className={`${className}${selected ? " sel" : ""}`} style={style} onClick={onSelect}>
      {dirty && <span className="pv-dirty">Unsaved edits</span>}
      {body}
    </section>
  );

  switch (type) {
    case "hero": {
      const bg = o(c.background);
      const bgSrc = bg.type === "video" ? resolveMedia(bg.posterUrl) : resolveMedia(bg.url);
      return wrap(
        "pv-hero",
        <>
          <div className="arc" />
          <div className="pv-nav">
            <span className="logo">Unionists</span>
            <span>About ▾</span>
            <span>Product & Services ▾</span>
            <span>Sustainability ▾</span>
            <span>Innovations & AI ▾</span>
            <span>Media & Insights ▾</span>
            <span>Global Presence</span>
            <span>Contact</span>
          </div>
          <h2>
            <Title t={c.title} />
          </h2>
          {s(c.subtitle) && <p>{s(c.subtitle)}</p>}
          <Ctas ctas={c.ctas} dark />
        </>,
        {
          backgroundColor: "#071430",
          backgroundImage: `${bgSrc ? `linear-gradient(rgba(7,20,48,.55),rgba(7,20,48,.75)), url("${bgSrc}")` : "radial-gradient(100% 120% at 50% 120%,#1e5bb8 0%,#0d2a5c 45%,#071430 80%)"}`,
          backgroundSize: "cover",
          backgroundPosition: "center",
        },
      );
    }

    case "stats":
      return wrap(
        "pv-stats",
        arr(c.items)
          .map(o)
          .map((x, i) => (
            <div className="s" key={i}>
              <div className="ic">
                <Media img={x.icon} className="pv-icon" fallbackIcon="chart" />
              </div>
              <b>{s(x.value)}</b>
              <span>{s(x.label)}</span>
            </div>
          )),
      );

    case "feature-cards": {
      const items = arr(c.items).map(o);
      const dark = sectionKey === "solutions";
      const cols = Math.min(Math.max(items.length, 1), dark ? 5 : 4);
      return wrap(
        dark ? "pv-dark" : "pv-features",
        <>
          {o(c.title).text ? (
            <h3>
              <Title t={c.title} />
            </h3>
          ) : null}
          <div className={dark ? "pv-offers" : "pv-badges"} style={{ gridTemplateColumns: `repeat(${cols}, 1fr)` }}>
            {items.map((x, i) =>
              dark ? (
                <div className="o" key={i}>
                  <div className="ic">
                    <Media img={x.icon} className="pv-icon" fallbackIcon="leaf" />
                  </div>
                  <h4>{s(x.title)}</h4>
                  <p>{s(x.description)}</p>
                </div>
              ) : (
                <div className="bd" key={i}>
                  <div className="ic">
                    <Media img={x.icon} className="pv-icon" fallbackIcon="award" />
                  </div>
                  <h4>{s(x.title)}</h4>
                  <p>{s(x.description)}</p>
                </div>
              ),
            )}
          </div>
          <Ctas ctas={c.ctas} dark={dark} />
        </>,
      );
    }

    case "text-image": {
      const img = <Media img={c.image} className="pv-img" />;
      const text = (
        <div>
          <h3>
            <Title t={c.title} />
          </h3>
          <Body text={c.body} />
        </div>
      );
      return wrap(
        "pv-split",
        c.imagePosition === "right" ? (
          <>
            {text}
            {img}
          </>
        ) : (
          <>
            {img}
            {text}
          </>
        ),
      );
    }

    case "logo-grid":
      return wrap(
        "pv-logos",
        <>
          <h3>
            <Title t={c.title} />
          </h3>
          <div className="lg">
            {arr(c.logos)
              .map(o)
              .map((x, i) => (
                <div className="l" key={i} title={s(x.name)}>
                  <Media img={x.image} className="pv-logo" fallbackIcon="building" />
                  {!resolveMedia(o(x.image).url) && s(x.name)}
                </div>
              ))}
          </div>
        </>,
      );

    case "cta-banner":
      return wrap(
        "pv-band",
        <>
          <h3>
            <Title t={c.title} />
          </h3>
          <Body text={c.body} />
          {s(o(c.cta).label) && <span className="btn btn-primary">{s(o(c.cta).label)}</span>}
        </>,
      );

    case "case-study":
      return wrap(
        "",
        <>
          <div className="pv-split">
            <div>
              <h3>
                <Title t={c.title} />
              </h3>
              <Body text={c.body} />
              <ul className="pv-list">
                {arr(c.bullets)
                  .map(s)
                  .filter(Boolean)
                  .map((b, i) => (
                    <li key={i}>
                      <Icon name="check" />
                      {b}
                    </li>
                  ))}
              </ul>
            </div>
            <Media img={c.image} className="pv-img" />
          </div>
          <div className="pv-case-cta">
            <Ctas ctas={c.ctas} />
          </div>
        </>,
      );

    case "contact":
      return wrap(
        "pv-contact",
        <>
          <div className="l">
            <h3>
              <Title t={c.title} />
            </h3>
            <Body text={c.body} className="intro" />
            {(
              [
                ["phone", "Phone Number:", s(c.phone)],
                ["mail", "Email:", s(c.email)],
                ["pin", "Location:", s(c.address)],
              ] as const
            )
              .filter(([, , v]) => v)
              .map(([icon, label, val]) => (
                <div className="ci" key={icon}>
                  <Icon name={icon} />
                  <div>
                    <span>{label}</span>
                    <b className="pv-body">{val}</b>
                  </div>
                </div>
              ))}
            <Ctas ctas={c.ctas} />
          </div>
          <div className="r">
            {s(c.formTitle) && <h3 style={{ textAlign: "center", marginBottom: 20 }}>{s(c.formTitle)}</h3>}
            {["Your Name", "Email Address", "Phone Number"].map((l) => (
              <div key={l}>
                <span className="flab">{l}</span>
                <div className="pv-f" />
              </div>
            ))}
            <span className="flab">Write Your Message</span>
            <div className="pv-f" style={{ height: 90 }} />
            <div style={{ textAlign: "center" }}>
              <span className="btn btn-primary">{s(c.submitLabel) || "Submit"}</span>
            </div>
          </div>
        </>,
      );

    case "footer": {
      const groups = arr(c.linkGroups).map(o);
      const social = arr(c.socialLinks).map(o);
      return wrap(
        "pv-footer",
        <>
          <div>
            <div className="logo" style={{ fontSize: 30, marginBottom: 16 }}>
              Unionists
            </div>
            <Body text={c.description} />
            {s(c.copyright) && <p style={{ marginTop: 20 }}>{s(c.copyright)}</p>}
          </div>
          {groups.map((g, i) => (
            <div key={i}>
              <h4>{s(g.title)}</h4>
              {arr(g.links)
                .map(o)
                .map((l, j) => (
                  <span key={j}>
                    {s(l.label)}
                    {l.openInNewTab ? " ↗" : ""}
                  </span>
                ))}
            </div>
          ))}
          {social.length > 0 && (
            <div>
              <h4>Social Links</h4>
              {social.map((l, j) => (
                <span key={j}>{s(l.label)} ↗</span>
              ))}
            </div>
          )}
        </>,
        { gridTemplateColumns: `1.6fr ${"1fr ".repeat(groups.length + (social.length ? 1 : 0)).trim()}` },
      );
    }

    case "page-hero":
      return wrap(
        "pv-pagehero",
        <>
          <h2>{s(c.title)}</h2>
          <p>Home › {s(c.breadcrumb)}</p>
        </>,
      );

    default:
      return wrap("pv-generic", <Generic c={c} />);
  }
}

/* ------------------------------------------------------------------ */
/* Inner page sections: one simplified layout for every other type     */
/* ------------------------------------------------------------------ */

/** A heading from a RichTitle or a plain string field. */
function Heading({ c }: { c: O }) {
  if (o(c.title).text) return <Title t={c.title} />;
  return <>{s(c.title) || s(c.heading) || s(c.label)}</>;
}

/** One card of a list section: whatever fields the item has, in a sensible order. */
function Card({ x }: { x: O }) {
  const img = o(x.image).url ? x.image : o(x.icon).url ? x.icon : null;
  const entries = arr(x.entries).map(o);
  const points = arr(x.points).map(o);
  const bullets = arr(x.bullets).map(s).filter(Boolean);
  const details = arr(x.details).map(o);
  const cells = arr(x.cells).map(s);
  const sub = [s(x.year), s(x.badge), s(x.label), s(x.period), s(x.area), s(x.location)].filter(Boolean).join(" · ");
  const stars = typeof x.rating === "number" ? "★".repeat(x.rating) : "";
  return (
    <div className="pv-item">
      {img ? <Media img={img} className={o(x.image).url ? "pv-item-img" : "pv-icon"} /> : null}
      {sub && <span className="pv-sub">{sub}</span>}
      {s(x.quote) && <p className="pv-quote">“{s(x.quote)}”</p>}
      {(s(x.title) || s(x.name)) && <h4>{s(x.title) || s(x.name)}</h4>}
      {(s(x.source) || s(x.role)) && <span className="pv-sub">— {[s(x.source), s(x.role)].filter(Boolean).join(", ")}</span>}
      {stars && <span className="pv-stars">{stars}</span>}
      {s(x.subtitle) && <p>{s(x.subtitle)}</p>}
      {s(x.description) && <p>{s(x.description)}</p>}
      {s(x.body) && <p className="pv-body">{s(x.body)}</p>}
      {details.map((d, i) => (
        <p key={i}>
          <b>{s(d.label)}</b> {s(d.text)}
        </p>
      ))}
      {(entries.length > 0 || points.length > 0 || bullets.length > 0 || cells.length > 0) && (
        <ul className="pv-list">
          {entries.map((e, i) => (
            <li key={`e${i}`}>
              <span>
                <b>{s(e.label)}</b>
                {s(e.detail) ? ` (${s(e.detail)})` : ""}
              </span>
            </li>
          ))}
          {points.map((p, i) => (
            <li key={`p${i}`}>
              <span>
                <b>{s(p.title)}</b>
                {s(p.description) ? ` — ${s(p.description)}` : ""}
              </span>
            </li>
          ))}
          {[...bullets, ...cells].map((b, i) => (
            <li key={`b${i}`}>
              <Icon name="check" />
              {b}
            </li>
          ))}
        </ul>
      )}
      {s(o(x.cta).label) && <span className="btn btn-outline">{s(o(x.cta).label)}</span>}
    </div>
  );
}

function Generic({ c }: { c: O }) {
  const items = arr(c.items).map(o);
  const columns = arr(c.columns).map(s);
  const rows = arr(c.rows).map(o);
  const featured = o(c.featured);
  const extras = [...arr(c.stats).map(o), ...arr(c.features).map(o)];
  const bullets = arr(c.bullets).map(s).filter(Boolean);
  const hasImage = !!s(o(c.image).url);
  const filterHeadings = Object.values(o(c.filterHeadings)).map(s).filter(Boolean);
  const text = (
    <div>
      <h3>
        <Heading c={c} />
      </h3>
      {s(c.lead) && <p className="pv-lead">{s(c.lead)}</p>}
      <Body text={c.body} />
      {bullets.length > 0 && (
        <ul className="pv-list">
          {bullets.map((b, i) => (
            <li key={i}>
              <Icon name="check" />
              {b}
            </li>
          ))}
        </ul>
      )}
      {s(c.note) && <p className="pv-lead">{s(c.note)}</p>}
      {extras.length > 0 && (
        <div className="pv-grid" style={{ gridTemplateColumns: `repeat(${Math.min(extras.length, 3)}, 1fr)` }}>
          {extras.map((x, i) => (
            <Card key={i} x={x} />
          ))}
        </div>
      )}
      {s(c.embedUrl) && <div className="pv-ph" style={{ height: 220, marginTop: 16 }}><span>Map: {s(c.label)}</span></div>}
      {typeof c.count === "number" && <div className="pv-ph" style={{ height: 120, marginTop: 16 }}><span>Latest {c.count} items</span></div>}
      {s(c.searchPlaceholder) && (
        <div className="pv-ph" style={{ height: 160, marginTop: 8 }}>
          <span>
            Product catalogue · {s(c.searchPlaceholder)} · {filterHeadings.join(" · ")}
          </span>
        </div>
      )}
      {s(c.allFilterLabel) && (
        <div className="pv-ph" style={{ height: 160, marginTop: 16 }}>
          <span>Articles · filter: {s(c.allFilterLabel)}</span>
        </div>
      )}
      {s(o(c.cta).label) && <div className="pv-ctas" style={{ justifyContent: "flex-start" }}><span className="btn btn-primary">{s(o(c.cta).label)}</span></div>}
      <Ctas ctas={c.ctas} />
    </div>
  );
  return (
    <>
      {hasImage ? (
        <div className="pv-split">
          {c.imagePosition === "right" ? (
            <>
              {text}
              <Media img={c.image} className="pv-img" />
            </>
          ) : (
            <>
              <Media img={c.image} className="pv-img" />
              {text}
            </>
          )}
        </div>
      ) : (
        <div className="pv-gen-text">{text}</div>
      )}
      {o(featured.image).url || s(featured.title) ? (
        <div className="pv-grid" style={{ gridTemplateColumns: "1fr" }}>
          <Card x={featured} />
        </div>
      ) : null}
      {columns.length > 0 && (
        <table className="pv-table">
          <thead>
            <tr>
              {columns.map((h, i) => (
                <th key={i}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i}>
                {arr(r.cells).map((cell, j) => (
                  <td key={j}>{s(cell)}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      )}
      {items.length > 0 && (
        <div className="pv-grid" style={{ gridTemplateColumns: `repeat(${Math.min(items.length, 3)}, 1fr)` }}>
          {items.map((x, i) => (
            <Card key={i} x={x} />
          ))}
        </div>
      )}
    </>
  );
}
