import {
  ContentStatus,
  type MagazineArticle,
  type MagazineArticleFaq,
  type MagazineArticleSection,
  type Media,
} from "@prisma/client";
import Link from "next/link";

import {
  deleteMagazineArticleAction,
  duplicateMagazineArticleAction,
  saveMagazineArticleAction,
} from "@/app/(admin)/admin/magazin/actions";
import { AdminDeleteButton } from "@/components/admin/common/AdminDeleteButton";
import { AdminSaveNotice } from "@/components/admin/common/AdminSaveNotice";
import { UnsavedChangesWatcher } from "@/components/admin/common/UnsavedChangesWatcher";
import { AdminDateTimeField } from "@/components/admin/forms/AdminDateTimeField";
import { MagazineArticleEditor } from "@/components/admin/magazine/MagazineArticleEditor";
import { MediaFieldPicker } from "@/components/admin/media/MediaFieldPicker";
import type { EntityAnalyticsSummary } from "@/lib/data/entity-analytics";
import { formatDateTimeLocalInput } from "@/lib/module-formatters";
import { SubmitButton } from "@/components/common/SubmitButton";

type EditionOption = {
  id: string;
  title: string;
};

type MagazineArticleDetails = MagazineArticle & {
  sections: MagazineArticleSection[];
  faqs: MagazineArticleFaq[];
  coverMedia?: Media | null;
};

// ─── Tokens ────────────────────────────────────────────────────────────────

const inputCls = "adminx-input";
const selectCls = "adminx-select";
const textareaCls = "adminx-textarea";

const STATUS_OPTIONS: Array<{ value: ContentStatus; label: string; color: string }> = [
  { value: ContentStatus.DRAFT, label: "Nacrt", color: "bg-amber-100 text-amber-800 border-amber-200" },
  { value: ContentStatus.PUBLISHED, label: "Objavljen", color: "bg-emerald-100 text-emerald-800 border-emerald-200" },
  { value: ContentStatus.ARCHIVED, label: "Arhiviran", color: "bg-slate-100 text-slate-700 border-slate-200" },
];

const LOCALE_OPTIONS = [
  { value: "sr", label: "Srpski (sr)" },
  { value: "en", label: "Engleski (en)" },
];

const REVIEW_STATUS_OPTIONS: Array<{ value: string; label: string; color: string }> = [
  { value: "", label: "Bez statusa", color: "bg-[#faf9f7] text-muted-foreground border-border" },
  {
    value: "IN_REVIEW",
    label: "Na review-u",
    color: "bg-blue-50 text-blue-700 border-blue-200",
  },
  {
    value: "APPROVED",
    label: "Odobreno",
    color: "bg-emerald-50 text-emerald-700 border-emerald-200",
  },
  {
    value: "NEEDS_CHANGES",
    label: "Treba dorada",
    color: "bg-amber-50 text-amber-800 border-amber-200",
  },
];

// ─── Section wrapper (FormSection pattern iz EventForm/RealEstateForm) ─────

function FormSection({
  title,
  icon,
  hint,
  action,
  children,
}: {
  title: string;
  icon: React.ReactNode;
  hint?: string;
  action?: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <section className="overflow-hidden rounded-2xl border border-border bg-white shadow-sm">
      <header className="flex items-start gap-3 border-b border-border bg-[#faf9f7] px-5 py-3.5">
        <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white text-primary shadow-sm border border-border/60">
          {icon}
        </div>
        <div className="min-w-0 flex-1">
          <h3 className="text-sm font-bold uppercase tracking-[0.12em] text-foreground">{title}</h3>
          {hint ? <p className="mt-1 text-xs leading-5 text-muted-foreground">{hint}</p> : null}
        </div>
        {action ? <div className="shrink-0">{action}</div> : null}
      </header>
      <div className="p-5">{children}</div>
    </section>
  );
}

function Field({
  label,
  hint,
  children,
  required,
  className,
}: {
  label: string;
  hint?: string;
  children: React.ReactNode;
  required?: boolean;
  className?: string;
}) {
  return (
    <div className={`space-y-1.5 ${className ?? ""}`}>
      <label className="flex items-center gap-2 text-xs font-bold uppercase tracking-[0.12em] text-foreground">
        {label}
        {required ? <span className="text-primary">*</span> : null}
      </label>
      {hint ? <p className="text-xs leading-5 text-muted-foreground">{hint}</p> : null}
      {children}
    </div>
  );
}

// ─── Main form ────────────────────────────────────────────────────────────

export function MagazineArticleForm({
  article,
  editions,
  analytics,
  magazineAuthors = [],
}: {
  article?: MagazineArticleDetails | null;
  editions: EditionOption[];
  analytics?: EntityAnalyticsSummary | null;
  /** Lista MagazineAuthor entiteta — za author/reviewedBy/factCheckedBy select. */
  magazineAuthors?: Array<{
    id: string;
    slug: string;
    name: string;
    jobTitle: string | null;
    photoUrl: string | null;
  }>;
}) {
  const isEdit = Boolean(article?.id);
  const currentStatus =
    STATUS_OPTIONS.find((s) => s.value === article?.status) ?? STATUS_OPTIONS[0]!;

  return (
    <div className="space-y-6">
      <form action={saveMagazineArticleAction} className="space-y-6">
        <UnsavedChangesWatcher />
        {article?.id ? <input type="hidden" name="id" value={article.id} /> : null}

        {/* ─── TOP BAR ─────────────────────────────────────────────── */}
        <div className="flex flex-wrap items-center gap-3 rounded-2xl border border-border bg-white px-5 py-4 shadow-sm">
          <Link
            href="/admin/magazin"
            className="inline-flex items-center gap-1.5 rounded-full border border-border bg-white px-3 py-1.5 text-xs font-semibold text-foreground transition hover:border-primary/40 hover:bg-[#fff4f0]"
          >
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="15 18 9 12 15 6" />
            </svg>
            Magazin
          </Link>
          <div className="min-w-0 flex-1">
            <p className="truncate text-base font-bold text-foreground">
              {isEdit ? (article?.title ?? "—") : "Novi članak"}
            </p>
            <p className="text-xs text-muted-foreground">
              {isEdit ? `Slug: ${article?.slug}` : "Premium magazine CMS"}
            </p>
          </div>
          {article ? (
            <span
              className={`inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs font-bold ${currentStatus.color}`}
            >
              <span className="h-1.5 w-1.5 rounded-full bg-current opacity-70" />
              {currentStatus.label}
            </span>
          ) : null}
          {article?.slug && article.status === ContentStatus.PUBLISHED ? (
            <a
              href={`/magazin/${article.slug}`}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 rounded-full border border-border bg-white px-3 py-1.5 text-xs font-semibold text-foreground transition hover:border-primary/40 hover:bg-[#fff4f0]"
            >
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                <polyline points="15 3 21 3 21 9" />
                <line x1="10" y1="14" x2="21" y2="3" />
              </svg>
              Otvori javnu stranu
            </a>
          ) : null}
          {article ? (
            <>
              {/* Duplicate button override-uje parent form action preko HTML
                  `formAction` atributa. Pre je bio nested <form action=...>
                  unutar Save <form action=...> — to HTML zabranjuje i izaziva
                  hydration error + continuous refresh. Sada button koristi
                  isti parent form (id polje već postoji u hidden input-u
                  iznad), samo prebacuje action na duplicateMagazineArticleAction
                  kad ga klikneš. */}
              <SubmitButton
                formAction={duplicateMagazineArticleAction}
                title="Dupliciraj kao novu skicu"
                className="inline-flex h-9 items-center gap-1.5 rounded-full border border-border bg-white px-3 text-xs font-semibold text-foreground transition hover:border-primary/40 hover:bg-[#fff4f0]"
              >
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
                </svg>
                Dupliciraj
              </SubmitButton>
              <AdminDeleteButton
                action={deleteMagazineArticleAction}
                title="Obrisati članak?"
                description="Članak će biti uklonjen iz magazina i javnog prikaza."
                triggerLabel="Obriši"
                inputs={[{ name: "id", value: article.id }]}
              />
            </>
          ) : null}
          <SubmitButton
            className="inline-flex h-9 items-center gap-2 rounded-full bg-primary px-5 text-sm font-bold text-white shadow-[0_8px_22px_rgba(194,65,12,0.28)] transition hover:bg-[#d94e22] active:scale-[0.97]"
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
              <polyline points="17 21 17 13 7 13 7 21" />
              <polyline points="7 3 7 8 15 8" />
            </svg>
            Sačuvaj članak
          </SubmitButton>
        </div>

        <AdminSaveNotice message="Članak je sačuvan." />

        {/* ─── 2-COLUMN LAYOUT ────────────────────────────────────── */}
        <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_360px] xl:grid-cols-[minmax(0,1fr)_400px]">
          {/* LEFT — main content */}
          <div className="min-w-0 space-y-5">
            {/* ── Hero — title + slug ──────────────────────────── */}
            <FormSection
              title="Naslov i URL"
              hint="Naslov je primarni SEO signal. Slug se automatski generiše iz naslova ako ostane prazan."
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="4" y1="9" x2="20" y2="9" />
                  <line x1="4" y1="15" x2="20" y2="15" />
                  <line x1="10" y1="3" x2="8" y2="21" />
                  <line x1="16" y1="3" x2="14" y2="21" />
                </svg>
              }
            >
              <div className="space-y-4">
                <Field label="Naslov članka" required>
                  <input
                    required
                    name="title"
                    defaultValue={article?.title ?? ""}
                    className={inputCls}
                    placeholder="npr. Lokalna SEO strategija za male biznise"
                  />
                </Field>
                <Field
                  label="URL slug"
                  hint="Deo URL-a posle /magazin/. Koristi mala slova i crtice."
                >
                  <div className="flex items-center gap-2 rounded-xl border border-border bg-white px-3.5 focus-within:border-primary/50 focus-within:ring-2 focus-within:ring-primary/15">
                    <span className="text-xs text-muted-foreground">biznisportal.rs/magazin/</span>
                    <input
                      name="slug"
                      defaultValue={article?.slug ?? ""}
                      className="h-10 flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground focus:outline-none"
                      placeholder="auto-iz-naslova"
                    />
                  </div>
                </Field>
              </div>
            </FormSection>

            {/* ── Article editor (visual sections + FAQ + key points etc.) ── */}
            <MagazineArticleEditor
              articleId={article?.id ?? null}
              initialSections={article?.sections ?? []}
              initialFaqs={article?.faqs ?? []}
              initialExcerpt={article?.excerpt ?? ""}
              initialTldr={(article as MagazineArticle & { tldr?: string | null })?.tldr ?? ""}
              initialKeyPoints={article?.keyPoints ?? []}
              initialSources={
                (article as MagazineArticle & { sourceUrls?: string[] })?.sourceUrls ?? []
              }
              initialTags={article?.tags ?? []}
              initialRelatedSlugs={article?.relatedSlugs ?? []}
              initialSeoTitle={article?.seoTitle ?? ""}
              initialSeoDescription={article?.seoDescription ?? ""}
              initialReadingMinutes={article?.readingMinutes ?? 5}
              initialTitle={article?.title ?? ""}
              initialCoverUrl={article?.coverMedia?.url ?? null}
              initialCoverAlt={article?.coverAlt ?? ""}
              initialWordGoal={
                (article as MagazineArticle & { wordGoal?: number })?.wordGoal ?? 0
              }
            />

            {/* ── Internal notes (admin-only) ─────────────────── */}
            <FormSection
              title="Interne napomene"
              hint="Vidljivo samo u admin panelu — ne renderuje se na public strani. Korisno za review pitanja, deadline napomene, izvore u radu."
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                  <polyline points="14 2 14 8 20 8" />
                  <line x1="12" y1="18" x2="12" y2="12" />
                  <line x1="9" y1="15" x2="15" y2="15" />
                </svg>
              }
            >
              <textarea
                name="internalNotes"
                rows={4}
                defaultValue={
                  (article as MagazineArticle & { internalNotes?: string | null })?.internalNotes ?? ""
                }
                className={`${textareaCls} min-h-32`}
                placeholder="Privatni notes, todo, deadline, source links u radu…"
              />
            </FormSection>
          </div>

          {/* RIGHT — sidebar */}
          <aside className="min-w-0 space-y-5">
            {/* ── Publication card ────────────────────────────── */}
            <FormSection
              title="Objava"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                </svg>
              }
            >
              <div className="space-y-4">
                <Field label="Status">
                  <select
                    name="status"
                    defaultValue={article?.status ?? ContentStatus.DRAFT}
                    className={selectCls}
                  >
                    {STATUS_OPTIONS.map((s) => (
                      <option key={s.value} value={s.value}>
                        {s.label}
                      </option>
                    ))}
                  </select>
                </Field>
                <AdminDateTimeField
                  name="publishedAt"
                  label="Datum i vreme objave"
                  defaultValue={formatDateTimeLocalInput(article?.publishedAt)}
                />
                {/* Scheduled publish indicator — kada je DRAFT + publishedAt
                    u budućnosti, znamo da cron-koji-radi-svake-5min će ga
                    objaviti tačno na taj datum. */}
                {article?.status === ContentStatus.DRAFT &&
                article?.publishedAt &&
                new Date(article.publishedAt).getTime() > new Date().getTime() ? (
                  <div className="flex items-start gap-2 rounded-xl border border-blue-200 bg-blue-50 px-3.5 py-2.5">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#1d4ed8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="mt-0.5 shrink-0">
                      <circle cx="12" cy="12" r="10" />
                      <polyline points="12 6 12 12 16 14" />
                    </svg>
                    <div className="min-w-0 flex-1">
                      <p className="text-xs font-bold text-blue-900">Zakazana objava</p>
                      <p className="mt-0.5 text-[0.7rem] text-blue-800">
                        Članak će automatski biti objavljen{" "}
                        <strong>
                          {new Date(article.publishedAt).toLocaleString("sr-Latn", {
                            day: "numeric",
                            month: "long",
                            year: "numeric",
                            hour: "2-digit",
                            minute: "2-digit",
                          })}
                        </strong>
                        . Cron tick svake 5 minuta.
                      </p>
                    </div>
                  </div>
                ) : null}
                <Field
                  label="Featured"
                  hint="Istaknute članke prikazujemo u hero sekciji magazina i na homepage-u."
                >
                  <label className="flex cursor-pointer items-center gap-3 rounded-xl border border-border bg-white px-3.5 py-2.5 transition hover:border-primary/40 hover:bg-[#fff4f0]">
                    <input
                      type="checkbox"
                      name="isFeatured"
                      defaultChecked={
                        (article as MagazineArticle & { isFeatured?: boolean })?.isFeatured ?? false
                      }
                      className="h-4 w-4 rounded border-border accent-primary"
                    />
                    <span className="text-sm font-semibold text-foreground">
                      Istakni na magazinu i homepage-u
                    </span>
                  </label>
                </Field>
              </div>
            </FormSection>

            {/* ── Review workflow ─────────────────────────────── */}
            <FormSection
              title="Editorial workflow"
              hint="Interni status pre objave. Ne kontroliše publish — koristi se za koordinaciju u timu."
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
                  <polyline points="22 4 12 14.01 9 11.01" />
                </svg>
              }
            >
              <div className="space-y-3">
                {REVIEW_STATUS_OPTIONS.map((opt) => {
                  const currentReview =
                    (article as MagazineArticle & { reviewStatus?: string | null })?.reviewStatus ?? "";
                  return (
                    <label
                      key={opt.value || "none"}
                      className={`flex cursor-pointer items-center gap-3 rounded-xl border px-3.5 py-2.5 transition ${opt.color} hover:opacity-90`}
                    >
                      <input
                        type="radio"
                        name="reviewStatus"
                        value={opt.value}
                        defaultChecked={currentReview === opt.value}
                        className="h-4 w-4 accent-primary"
                      />
                      <span className="text-sm font-semibold">{opt.label}</span>
                    </label>
                  );
                })}
              </div>
            </FormSection>

            {/* ── Analytics (read-only summary) ────────────────── */}
            {analytics && article ? (
              <FormSection
                title="Analytics — poslednjih 30 dana"
                hint='Realtime pregled performansi članka. Klikni „Detaljno" za pun timeline.'
                icon={
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <line x1="18" y1="20" x2="18" y2="10" />
                    <line x1="12" y1="20" x2="12" y2="4" />
                    <line x1="6" y1="20" x2="6" y2="14" />
                  </svg>
                }
              >
                <AnalyticsSummaryCard summary={analytics} />
              </FormSection>
            ) : null}

            {/* ── Cover media ─────────────────────────────────── */}
            <FormSection
              title="Cover slika"
              hint="Hero slika članka (preporučeno 1600×900). Renderuje se kao social share preview na Facebook-u, Twitter-u, LinkedIn-u."
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="3" width="18" height="18" rx="2" />
                  <circle cx="8.5" cy="8.5" r="1.5" />
                  <polyline points="21 15 16 10 5 21" />
                </svg>
              }
            >
              <div className="space-y-4">
                <MediaFieldPicker
                  name="coverMediaId"
                  label=""
                  directory={`magazine/articles/${article?.id ?? "draft"}`}
                  initialId={article?.coverMediaId ?? undefined}
                  initialUrl={article?.coverMedia?.url}
                />
                <Field
                  label="Alt tekst"
                  hint="Opis slike za screen reader-e i SEO. Obavezno za pristupačnost."
                >
                  <input
                    name="coverAlt"
                    defaultValue={article?.coverAlt ?? ""}
                    className={inputCls}
                    placeholder="npr. Tim za marketing na sastanku, laptop sa grafikonima"
                  />
                </Field>
                <Field label="Caption" hint="Opcioni potpis ispod slike.">
                  <input
                    name="coverCaption"
                    defaultValue={article?.coverCaption ?? ""}
                    className={inputCls}
                    placeholder="Foto: BiznisPortal redakcija"
                  />
                </Field>
              </div>
            </FormSection>

            {/* ── Author ────────────────────────────────────── */}
            <FormSection
              title="Autor članka (E-E-A-T)"
              hint="Glavni autor + peer reviewer + fact-checker — Google E-E-A-T algoritam ovo računa kao autoritet."
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
                  <circle cx="12" cy="7" r="4" />
                </svg>
              }
            >
              <div className="space-y-4">
                {/* Primary author (full entity sa LinkedIn/bio iz MagazineAuthor) */}
                <Field
                  label="Glavni autor (preporučeno)"
                  hint={
                    magazineAuthors.length === 0
                      ? "Nema kreiranih autora — idi na /admin/autori da dodaš."
                      : "Override-uje stari authorName ako je popunjen."
                  }
                >
                  <select
                    name="authorId"
                    defaultValue={
                      (article as MagazineArticle & { authorId?: string | null })?.authorId ?? ""
                    }
                    className={inputCls}
                  >
                    <option value="">— Bez autora (koristi stari Ime/Titula fallback) —</option>
                    {magazineAuthors.map((a) => (
                      <option key={a.id} value={a.id}>
                        {a.name}
                        {a.jobTitle ? ` · ${a.jobTitle}` : ""}
                      </option>
                    ))}
                  </select>
                </Field>

                {/* Peer reviewer */}
                <Field label="Pregledao (peer review)" hint="Drugi član editorial-a koji je verifikovao članak. Schema.org Article.reviewedBy.">
                  <select
                    name="reviewedById"
                    defaultValue={
                      (article as MagazineArticle & { reviewedById?: string | null })?.reviewedById ?? ""
                    }
                    className={inputCls}
                  >
                    <option value="">— Bez review-a —</option>
                    {magazineAuthors.map((a) => (
                      <option key={a.id} value={a.id}>
                        {a.name}
                      </option>
                    ))}
                  </select>
                </Field>

                {/* Fact-checker */}
                <Field label="Fact-checker" hint="Osoba koja je proverila tačnost činjenica.">
                  <select
                    name="factCheckedById"
                    defaultValue={
                      (article as MagazineArticle & { factCheckedById?: string | null })?.factCheckedById ?? ""
                    }
                    className={inputCls}
                  >
                    <option value="">— Bez fact-check-a —</option>
                    {magazineAuthors.map((a) => (
                      <option key={a.id} value={a.id}>
                        {a.name}
                      </option>
                    ))}
                  </select>
                </Field>

                <div className="rounded-xl border border-amber-200 bg-amber-50/60 px-3 py-2 text-xs text-amber-900">
                  ⚠️ Stara polja (Ime / Titula / URL) su LEGACY fallback. Ako popuniš
                  „Glavni autor" iznad — to override-uje legacy polja na public stranici.
                </div>

                <Field label="Ime autora (legacy fallback)">
                  <input
                    name="authorName"
                    defaultValue={article?.authorName ?? ""}
                    className={inputCls}
                    placeholder="BiznisPortal redakcija"
                  />
                </Field>
                <Field label="Titula" hint="npr. Glavni urednik, CEO Smartechor">
                  <input
                    name="authorTitle"
                    defaultValue={
                      (article as MagazineArticle & { authorTitle?: string | null })?.authorTitle ??
                      ""
                    }
                    className={inputCls}
                    placeholder="Konsultant • Strategija"
                  />
                </Field>
                <Field label="URL fotografije" hint="Direktan link na avatar (kvadratni format).">
                  <input
                    type="url"
                    name="authorImageUrl"
                    defaultValue={
                      (article as MagazineArticle & { authorImageUrl?: string | null })
                        ?.authorImageUrl ?? ""
                    }
                    className={inputCls}
                    placeholder="https://cdn.../autor.jpg"
                  />
                </Field>
              </div>
            </FormSection>

            {/* ── Klasifikacija ────────────────────────────── */}
            <FormSection
              title="Klasifikacija"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z" />
                  <line x1="7" y1="7" x2="7.01" y2="7" />
                </svg>
              }
            >
              <div className="space-y-4">
                <Field label="Kategorija" required>
                  <input
                    required
                    name="category"
                    defaultValue={article?.category ?? ""}
                    className={inputCls}
                    placeholder="npr. Marketing, Pravo, Finansije"
                  />
                </Field>
                <Field label="Jezik">
                  <select
                    name="locale"
                    defaultValue={
                      (article as MagazineArticle & { locale?: string })?.locale ?? "sr"
                    }
                    className={selectCls}
                  >
                    {LOCALE_OPTIONS.map((opt) => (
                      <option key={opt.value} value={opt.value}>
                        {opt.label}
                      </option>
                    ))}
                  </select>
                </Field>
                <Field label="PDF izdanje" hint="Opciono — veza sa magazin PDF izdanjem.">
                  <select name="editionId" defaultValue={article?.editionId ?? ""} className={selectCls}>
                    <option value="">Bez PDF izdanja</option>
                    {editions.map((edition) => (
                      <option key={edition.id} value={edition.id}>
                        {edition.title}
                      </option>
                    ))}
                  </select>
                </Field>
              </div>
            </FormSection>

            {/* ── Article info (read-only) ──────────────────── */}
            {article ? (
              <FormSection
                title="Info"
                icon={
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="12" cy="12" r="10" />
                    <line x1="12" y1="16" x2="12" y2="12" />
                    <line x1="12" y1="8" x2="12.01" y2="8" />
                  </svg>
                }
              >
                <dl className="space-y-2 text-xs">
                  <InfoRow label="ID" value={article.id} mono />
                  <InfoRow
                    label="Kreiran"
                    value={article.createdAt ? new Date(article.createdAt).toLocaleString("sr-Latn") : "—"}
                  />
                  <InfoRow
                    label="Poslednja izmena"
                    value={article.updatedAt ? new Date(article.updatedAt).toLocaleString("sr-Latn") : "—"}
                  />
                  <InfoRow label="Vreme čitanja" value={`${article.readingMinutes} min`} />
                  <InfoRow label="Broj sekcija" value={String(article.sections.length)} />
                  <InfoRow label="FAQ pitanja" value={String(article.faqs.length)} />
                </dl>
              </FormSection>
            ) : null}
          </aside>
        </div>

        {/* Footer save bar */}
        <div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-border bg-white px-5 py-4 shadow-sm">
          <p className="text-xs text-muted-foreground">
            Sve promene postaju vidljive nakon klika „Sačuvaj članak".
          </p>
          <SubmitButton
            className="inline-flex h-10 items-center gap-2 rounded-full bg-primary px-6 text-sm font-bold text-white shadow-[0_8px_22px_rgba(194,65,12,0.28)] transition hover:bg-[#d94e22] active:scale-[0.97]"
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
              <polyline points="17 21 17 13 7 13 7 21" />
              <polyline points="7 3 7 8 15 8" />
            </svg>
            Sačuvaj članak
          </SubmitButton>
        </div>
      </form>
    </div>
  );
}

function InfoRow({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) {
  return (
    <div className="flex items-center justify-between gap-3">
      <dt className="font-semibold uppercase tracking-[0.1em] text-muted-foreground">{label}</dt>
      <dd className={`truncate text-right text-foreground ${mono ? "font-mono" : "font-medium"}`}>{value}</dd>
    </div>
  );
}

/** Kompaktni analytics summary za sidebar — sve ključne metrike + chart. */
function AnalyticsSummaryCard({ summary }: { summary: EntityAnalyticsSummary }) {
  const last14Views = summary.viewTimeline?.slice(-14) ?? [];
  const maxViews = Math.max(1, ...last14Views.map((d) => d.count));
  const last14ViewsTotal = last14Views.reduce((sum, d) => sum + d.count, 0);
  // All-time totals iz summary-ja (NE samo 14d) — daju pravu sliku
  // popularnosti članka kroz ceo život na sajtu.
  const totalAllTimeViews = summary.totals?.VIEW ?? 0;
  const totalUniqueReaders = summary.totalUniqueVisitors ?? 0;
  const last30DaysTotal = summary.last30DaysTotal ?? 0;
  const last30DaysUniques = summary.last30DaysUniqueVisitors ?? 0;
  // actionRows je top-level CTA breakdown — uzimamo top 4 po total
  const topActions = (summary.actionRows ?? []).slice(0, 4);
  const totalActions = topActions.reduce((sum, a) => sum + a.total, 0);
  const ctr =
    totalAllTimeViews > 0 ? Math.round((totalActions / totalAllTimeViews) * 100) : 0;
  // Reading time metrika iz ReadingSession agregata.
  const reading = summary.reading ?? {
    totalSec: 0,
    totalSessions: 0,
    averageSec: 0,
    averageScrollDepthPct: 0,
    last30DaysTotalSec: 0,
    last30DaysSessions: 0,
  };

  // Formatiraj sekunde → human-readable: 12h 34m, 3m 24s, 45s
  const formatDuration = (sec: number) => {
    if (sec < 60) return `${sec}s`;
    if (sec < 3600) {
      const m = Math.floor(sec / 60);
      const s = sec % 60;
      return s > 0 ? `${m}m ${s}s` : `${m}m`;
    }
    const h = Math.floor(sec / 3600);
    const m = Math.floor((sec % 3600) / 60);
    return m > 0 ? `${h}h ${m}m` : `${h}h`;
  };

  return (
    <div className="space-y-4">
      {/* Glavne metrike — pregled svih vremena + 30 dana */}
      <div className="grid grid-cols-2 gap-3">
        <MetricTile
          label="Pregleda (svih vr.)"
          value={totalAllTimeViews.toLocaleString("sr-Latn")}
          accent="primary"
        />
        <MetricTile
          label="Jedinstv. čitalaca"
          value={totalUniqueReaders.toLocaleString("sr-Latn")}
          accent="emerald"
        />
        <MetricTile
          label="Pregleda (30d)"
          value={last30DaysTotal.toLocaleString("sr-Latn")}
          accent="blue"
        />
        <MetricTile
          label="Jedinstv. (30d)"
          value={last30DaysUniques.toLocaleString("sr-Latn")}
          accent="amber"
        />
        <MetricTile
          label="Pregleda (14d)"
          value={last14ViewsTotal.toLocaleString("sr-Latn")}
          accent="primary"
        />
        <MetricTile label="CTR akcija" value={`${ctr}%`} accent="emerald" />
      </div>

      {/* ── Reading time metrics ──────────────────────────────────────
          Vidljivo samo ako ima makar 1 sesija (ReadingTracker je počeo
          da skuplja podatke). Inače blok se preskače. */}
      {reading.totalSessions > 0 ? (
        <div className="rounded-xl border border-primary/15 bg-[#fff8f5] px-3 py-3">
          <p className="mb-3 text-[0.62rem] font-bold uppercase tracking-[0.14em] text-primary/80">
            📖 Čitanje članka
          </p>
          <div className="grid grid-cols-2 gap-3">
            <MetricTile
              label="Ukupno vremena"
              value={formatDuration(reading.totalSec)}
              accent="primary"
            />
            <MetricTile
              label="Broj sesija"
              value={reading.totalSessions.toLocaleString("sr-Latn")}
              accent="emerald"
            />
            <MetricTile
              label="Prosečno čitanje"
              value={formatDuration(reading.averageSec)}
              accent="blue"
            />
            <MetricTile
              label="Prosečni scroll"
              value={`${reading.averageScrollDepthPct}%`}
              accent="amber"
            />
          </div>
          {reading.last30DaysSessions > 0 ? (
            <p className="mt-3 text-[0.62rem] text-muted-foreground">
              Poslednjih 30 dana: {reading.last30DaysSessions} sesija ·{" "}
              {formatDuration(reading.last30DaysTotalSec)} čitanja
            </p>
          ) : null}
        </div>
      ) : null}

      {/* Mini bar chart — last 14d views */}
      {last14Views.length > 0 ? (
        <div className="rounded-xl border border-border bg-white px-3 py-3">
          <div className="mb-2 flex items-center justify-between">
            <p className="text-[0.62rem] font-bold uppercase tracking-[0.14em] text-muted-foreground">
              Pregledi po danu
            </p>
            <p className="text-[0.7rem] text-muted-foreground">max {maxViews}</p>
          </div>
          <div className="flex items-end gap-1 h-16">
            {last14Views.map((day, i) => {
              const height = (day.count / maxViews) * 100;
              return (
                <div
                  key={`${day.date}-${i}`}
                  className="flex-1 rounded-sm bg-gradient-to-t from-primary/30 to-primary"
                  style={{ height: `${Math.max(4, height)}%` }}
                  title={`${day.date}: ${day.count}`}
                />
              );
            })}
          </div>
        </div>
      ) : null}

      {/* Top actions */}
      {topActions.length > 0 ? (
        <div className="rounded-xl border border-border bg-white px-3 py-3">
          <p className="mb-2 text-[0.62rem] font-bold uppercase tracking-[0.14em] text-muted-foreground">
            Top akcije
          </p>
          <ul className="space-y-1.5 text-xs">
            {topActions.map((action) => (
              <li key={action.action} className="flex items-center justify-between gap-2">
                <span className="font-medium text-foreground">{action.label}</span>
                <span className="font-bold text-foreground">{action.total.toLocaleString("sr-Latn")}</span>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
    </div>
  );
}

function MetricTile({
  label,
  value,
  accent,
}: {
  label: string;
  value: string;
  accent: "primary" | "emerald" | "blue" | "amber";
}) {
  const accentMap = {
    primary: "border-[#c2410c]/20 bg-[#fff4f0] text-foreground",
    emerald: "border-emerald-200 bg-emerald-50 text-emerald-900",
    blue: "border-blue-200 bg-blue-50 text-blue-900",
    amber: "border-amber-200 bg-amber-50 text-amber-900",
  } as const;
  return (
    <div className={`rounded-xl border px-3 py-2.5 ${accentMap[accent]}`}>
      <p className="text-[0.6rem] font-bold uppercase tracking-[0.14em] opacity-70">{label}</p>
      <p className="mt-1 text-lg font-bold">{value}</p>
    </div>
  );
}
