"use client";
import { useEffect, useRef, useState } from "react";

export default function AdminSettingsPage() {
  const [siteName, setSiteName] = useState("");
  const [defaultFontScaleIndex, setDefaultFontScaleIndex] = useState(1);
  const [notifyNewMembersOfMissions, setNotifyNewMembersOfMissions] = useState(true);
  const [maxImageMb, setMaxImageMb] = useState(10);
  const [maxVideoMb, setMaxVideoMb] = useState(100);
  const [freeEbookProductId, setFreeEbookProductId] = useState("");
  const [tipShortLinkSlug, setTipShortLinkSlug] = useState("abcd");
  const [tipPresetAmounts, setTipPresetAmounts] = useState<{ amount: number; emoji: string }[]>([
    { amount: 5, emoji: "" }, { amount: 10, emoji: "" }, { amount: 25, emoji: "" },
    { amount: 50, emoji: "" }, { amount: 100, emoji: "" }, { amount: 200, emoji: "" },
  ]);
  const [tipVipPresetAmounts, setTipVipPresetAmounts] = useState<{ amount: number; emoji: string }[]>([
    { amount: 500, emoji: "" }, { amount: 1000, emoji: "" }, { amount: 2500, emoji: "" },
  ]);
  const [tipNormalPopupGif, setTipNormalPopupGif] = useState("");
  const [tipVipPopupGif, setTipVipPopupGif] = useState("");
  const [tipPopupDurationSeconds, setTipPopupDurationSeconds] = useState(2);
  const [uploadingNormalGif, setUploadingNormalGif] = useState(false);
  const [uploadingVipGif, setUploadingVipGif] = useState(false);
  const [tipVipBoxTitle, setTipVipBoxTitle] = useState("Special VIP Donators");
  const [tipHumbleEnabled, setTipHumbleEnabled] = useState(true);
  const [tipHumbleTitle, setTipHumbleTitle] = useState("I can't give much, but I'll do my best to help.");
  const [tipHumbleAmount, setTipHumbleAmount] = useState(2);
  const [tipNormalGifLength, setTipNormalGifLength] = useState("");
  const [tipVipGifLength, setTipVipGifLength] = useState("");
  const [tipSuccessGif, setTipSuccessGif] = useState("");
  const [tipSuccessGifLength, setTipSuccessGifLength] = useState("");
  const [tipSuccessSound, setTipSuccessSound] = useState("");
  const [tipSuccessDurationSeconds, setTipSuccessDurationSeconds] = useState(3);
  const [upgradeSuccessGif, setUpgradeSuccessGif] = useState("");
  const [upgradeSuccessGifLength, setUpgradeSuccessGifLength] = useState("");
  const [upgradeSuccessSound, setUpgradeSuccessSound] = useState("");
  const [upgradeSuccessDurationSeconds, setUpgradeSuccessDurationSeconds] = useState(3);
  const [uploadingSuccessGif, setUploadingSuccessGif] = useState(false);
  const [uploadingUpgradeGif, setUploadingUpgradeGif] = useState(false);
  const [tipNormalClickSound, setTipNormalClickSound] = useState("");
  const [tipVipClickSound, setTipVipClickSound] = useState("");
  const [uploadingNormalSound, setUploadingNormalSound] = useState(false);
  const [uploadingVipSound, setUploadingVipSound] = useState(false);
  const [digitalProducts, setDigitalProducts] = useState<any[]>([]);
  const [tagline, setTagline] = useState("");
  const [gradientIntensity, setGradientIntensity] = useState(20);
  const [defaultPreviewSeconds, setDefaultPreviewSeconds] = useState(0);
  const [marqueeSeconds, setMarqueeSeconds] = useState(25);
  const [notifyEmail1, setNotifyEmail1] = useState("");
  const [notifyEmail2, setNotifyEmail2] = useState("");
  const [notifyEmail3, setNotifyEmail3] = useState("");
  const [badgeIconUrl, setBadgeIconUrl] = useState("");
  const [uploadingBadge, setUploadingBadge] = useState(false);
  const [tipOtherLabel, setTipOtherLabel] = useState("Other");
  const [communityRequestBase, setCommunityRequestBase] = useState(1234);
  const [communityPrayerBase, setCommunityPrayerBase] = useState(123456);
  const [supporterBadgeSize, setSupporterBadgeSize] = useState(13);
  const [badgeTiers, setBadgeTiers] = useState<{ min: number; max: number | null; crosses: number }[]>([
    { min: 1, max: 10, crosses: 1 },
    { min: 10, max: 100, crosses: 2 },
    { min: 100, max: null, crosses: 3 },
  ]);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const badgeFileRef = useRef<HTMLInputElement>(null);
  const [companyName, setCompanyName] = useState("");
  const [companyUrl, setCompanyUrl] = useState("");
  const [pageAboutContent, setPageAboutContent] = useState("");
  const [pageContactContent, setPageContactContent] = useState("");
  const [pageTermsContent, setPageTermsContent] = useState("");
  const [pagePrivacyContent, setPagePrivacyContent] = useState("");
  const [pageRefundContent, setPageRefundContent] = useState("");

  useEffect(() => {
    fetch("/api/admin/settings")
      .then((r) => r.json())
      .then((d) => {
        setSiteName(d.siteName || "");
        setDefaultFontScaleIndex(d.defaultFontScaleIndex ?? 1);
        setNotifyNewMembersOfMissions(d.notifyNewMembersOfMissions ?? true);
        setMaxImageMb(d.maxImageMb ?? 10);
        setMaxVideoMb(d.maxVideoMb ?? 100);
        setFreeEbookProductId(d.freeEbookProductId || "");
        setTipShortLinkSlug(d.tipShortLinkSlug || "abcd");
        if (d.tipPresetAmounts) {
          try {
            const parsed = JSON.parse(d.tipPresetAmounts);
            setTipPresetAmounts(parsed.map((b: any) => (typeof b === "number" ? { amount: b, emoji: "" } : { amount: b.amount, emoji: b.emoji || "" })));
          } catch {}
        }
        if (d.tipVipPresetAmounts) {
          try {
            const parsed = JSON.parse(d.tipVipPresetAmounts);
            setTipVipPresetAmounts(parsed.map((b: any) => (typeof b === "number" ? { amount: b, emoji: "" } : { amount: b.amount, emoji: b.emoji || "" })));
          } catch {}
        }
        setTipNormalClickSound(d.tipNormalClickSound || "");
        setTipVipClickSound(d.tipVipClickSound || "");
        setTipNormalPopupGif(d.tipNormalPopupGif || "");
        setTipVipPopupGif(d.tipVipPopupGif || "");
        setTipPopupDurationSeconds(parseFloat(d.tipPopupDurationSeconds) || 2);
        setTipVipBoxTitle(d.tipVipBoxTitle || "Special VIP Donators");
        setTipHumbleEnabled(d.tipHumbleEnabled !== "false");
        setTipHumbleTitle(d.tipHumbleTitle || "I can't give much, but I'll do my best to help.");
        setTipHumbleAmount(parseFloat(d.tipHumbleAmount) || 2);
        setTipNormalGifLength(d.tipNormalGifLength || "");
        setTipVipGifLength(d.tipVipGifLength || "");
        setTipSuccessGif(d.tipSuccessGif || "");
        setTipSuccessGifLength(d.tipSuccessGifLength || "");
        setTipSuccessSound(d.tipSuccessSound || "");
        setTipSuccessDurationSeconds(parseFloat(d.tipSuccessDurationSeconds) || 3);
        setUpgradeSuccessGif(d.upgradeSuccessGif || "");
        setUpgradeSuccessGifLength(d.upgradeSuccessGifLength || "");
        setUpgradeSuccessSound(d.upgradeSuccessSound || "");
        setUpgradeSuccessDurationSeconds(parseFloat(d.upgradeSuccessDurationSeconds) || 3);
        setTagline(d.tagline || "");
        setGradientIntensity(d.bgGradientIntensity ?? 20);
        setDefaultPreviewSeconds(d.defaultPreviewSeconds ?? 0);
        setMarqueeSeconds(d.marqueeSeconds ?? 25);
        setNotifyEmail1(d.notifyEmail1 || "");
        setNotifyEmail2(d.notifyEmail2 || "");
        setNotifyEmail3(d.notifyEmail3 || "");
        setBadgeIconUrl(d.badgeIconUrl || "");
        setTipOtherLabel(d.tipOtherLabel || "Other");
        setCommunityRequestBase(d.communityRequestBase ?? 1234);
        setCommunityPrayerBase(d.communityPrayerBase ?? 123456);
        setSupporterBadgeSize(d.supporterBadgeSize ?? 13);
        if (d.badgeTiers) {
          try { setBadgeTiers(JSON.parse(d.badgeTiers)); } catch {}
        }
        setCompanyName(d.companyName || "");
        setCompanyUrl(d.companyUrl || "");
        setPageAboutContent(d.pageAboutContent || "");
        setPageContactContent(d.pageContactContent || "");
        setPageTermsContent(d.pageTermsContent || "");
        setPagePrivacyContent(d.pagePrivacyContent || "");
        setPageRefundContent(d.pageRefundContent || "");
      });
    fetch("/api/admin/products")
      .then((r) => r.json())
      .then((d) => setDigitalProducts(Array.isArray(d) ? d.filter((p: any) => p.type === "digital") : []));
  }, []);

  async function handleBadgeUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploadingBadge(true);
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch("/api/upload", { method: "POST", body: formData });
    const data = await res.json();
    setUploadingBadge(false);
    if (res.ok) setBadgeIconUrl(data.url);
    e.target.value = "";
  }

  async function save() {
    setSaving(true);
    setSaved(false);
    await fetch("/api/admin/settings", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        siteName, tagline, bgGradientIntensity: gradientIntensity, defaultPreviewSeconds, marqueeSeconds,
        notifyEmail1, notifyEmail2, notifyEmail3, badgeIconUrl, tipOtherLabel,
        communityRequestBase, communityPrayerBase, supporterBadgeSize, badgeTiers: JSON.stringify(badgeTiers),
        defaultFontScaleIndex,
        notifyNewMembersOfMissions, maxImageMb, maxVideoMb, freeEbookProductId, tipShortLinkSlug, tipPresetAmounts,
        tipVipPresetAmounts, tipNormalClickSound, tipVipClickSound, tipNormalPopupGif, tipVipPopupGif, tipPopupDurationSeconds,
        tipVipBoxTitle, tipHumbleEnabled, tipHumbleTitle, tipHumbleAmount, tipNormalGifLength, tipVipGifLength,
        tipSuccessGif, tipSuccessGifLength, tipSuccessSound, tipSuccessDurationSeconds,
        upgradeSuccessGif, upgradeSuccessGifLength, upgradeSuccessSound, upgradeSuccessDurationSeconds,
        companyName, companyUrl, pageAboutContent, pageContactContent, pageTermsContent, pagePrivacyContent, pageRefundContent,
      }),
    });
    setSaving(false);
    setSaved(true);
  }

  const inputCls =
    "w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600";

  const [activeTab, setActiveTab] = useState<"general" | "payments" | "community" | "tips" | "pages">("general");

  const TABS: { key: "general" | "payments" | "community" | "tips" | "pages"; label: string; icon: string }[] = [
    { key: "general", label: "General", icon: "⚙️" },
    { key: "community", label: "Community", icon: "🙏" },
    { key: "payments", label: "Payments & Uploads", icon: "💳" },
    { key: "tips", label: "Tips & Donations", icon: "🎁" },
    { key: "pages", label: "Footer & Pages", icon: "📄" },
  ];

  const textareaCls =
    "w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600 font-mono";

  return (
    <div className="max-w-xl">
      <div className="sticky top-0 z-10 bg-[#0a0a0a] pb-3 pt-1 mb-3 flex gap-2 border-b border-neutral-800 overflow-x-auto">
        {TABS.map((tab) => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            className={`px-4 py-2 text-sm rounded-full whitespace-nowrap flex items-center gap-1.5 ${activeTab === tab.key ? "bg-red-600 text-white" : "bg-neutral-900 text-neutral-400 hover:bg-neutral-800"}`}
          >
            <span>{tab.icon}</span>
            {tab.label}
          </button>
        ))}
      </div>
      <h2 className="text-lg font-semibold mb-4">Site Settings</h2>
      <div className={`card p-5 space-y-6 ${activeTab === "general" ? "" : "hidden"}`} data-tab="general">
        <div>
          <label className="block text-xs text-neutral-500 mb-1.5">Site name (shown in sidebar, login, and signup pages)</label>
          <input value={siteName} onChange={(e) => setSiteName(e.target.value)} className={inputCls} />
          <p className="text-xs text-neutral-600 mt-1">The first letter is highlighted in red automatically.</p>
        </div>
        <div>
          <label className="block text-xs text-neutral-500 mb-1.5">Tagline (optional)</label>
          <input value={tagline} onChange={(e) => setTagline(e.target.value)} className={inputCls} />
        </div>
        <div>
          <label className="block text-xs text-neutral-500 mb-1.5">
            Background red glow intensity: {gradientIntensity}%
          </label>
          <input
            type="range"
            min="0"
            max="100"
            value={gradientIntensity}
            onChange={(e) => setGradientIntensity(parseInt(e.target.value))}
            className="w-full accent-red-600"
          />
          <div
            className="mt-3 h-16 rounded-lg border border-neutral-800"
            style={{
              background: `radial-gradient(ellipse 300px 150px at 50% 0%, rgba(220,38,38,${(gradientIntensity / 100) * 0.35}) 0%, transparent 65%), #0a0a0a`,
            }}
          />
          <p className="text-xs text-neutral-600 mt-1">Preview of the subtle red glow behind the main site's black background.</p>
        </div>
        <div>
          <label className="block text-xs text-neutral-500 mb-1.5">
            Default free-preview length for videos (seconds)
          </label>
          <input
            type="number"
            min="0"
            value={defaultPreviewSeconds}
            onChange={(e) => setDefaultPreviewSeconds(parseInt(e.target.value) || 0)}
            className={inputCls}
          />
          <p className="text-xs text-neutral-600 mt-1">
            Applies to any video where you haven't set a specific preview length. Set to 0 to disable
            previews site-wide by default (0 = no preview, video stays fully locked).
          </p>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "payments" ? "" : "hidden"}`} data-tab="payments">
        <h3 className="font-bold mb-1">Payment Notification Emails</h3>
        <p className="text-xs text-neutral-500 mb-4">
          A short "New payment received" email (amount + type only) is sent to these addresses every
          time a subscription, tip, or purchase is confirmed. Leave any blank to skip it.
        </p>
        <div className="space-y-3">
          <input value={notifyEmail1} onChange={(e) => setNotifyEmail1(e.target.value)} placeholder="admin1@yourdomain.com" className={inputCls} />
          <input value={notifyEmail2} onChange={(e) => setNotifyEmail2(e.target.value)} placeholder="admin2@yourdomain.com" className={inputCls} />
          <input value={notifyEmail3} onChange={(e) => setNotifyEmail3(e.target.value)} placeholder="admin3@yourdomain.com" className={inputCls} />
        </div>
      </div>

      <div className={`card p-5 mt-6 border-amber-800/40 bg-gradient-to-br from-amber-950/30 to-transparent ${activeTab === "general" ? "" : "hidden"}`} data-tab="general">
        <div className="flex items-center gap-2 mb-1">
          <span className="text-amber-400 text-lg">⭐</span>
          <h3 className="font-bold text-amber-100">Partners in Mission — Scroll Speed</h3>
        </div>
        <p className="text-xs text-neutral-500 mb-4">
          Controls how fast the "Supported Users" and "Top Performers" lists auto-scroll in the
          community sidebar. Lower = faster, higher = slower.
        </p>
        <label className="block text-xs text-amber-200 mb-1.5">
          Scroll duration: {marqueeSeconds} seconds per loop
        </label>
        <div className="flex items-center gap-3">
          <input
            type="range"
            min="5"
            max="2000"
            value={marqueeSeconds}
            onChange={(e) => setMarqueeSeconds(parseInt(e.target.value))}
            className="flex-1 accent-amber-500"
          />
          <input
            type="number"
            min="5"
            max="2000"
            value={marqueeSeconds}
            onChange={(e) => setMarqueeSeconds(Math.max(5, Math.min(2000, parseInt(e.target.value) || 5)))}
            className="w-20 bg-neutral-900 border border-amber-800/50 rounded-md px-2 py-1.5 text-sm text-center outline-none focus:border-amber-500"
          />
        </div>
        <div className="flex justify-between text-[10px] text-neutral-600 mt-1">
          <span>Fast (5s)</span>
          <span>Very Slow (2000s)</span>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "community" ? "" : "hidden"}`} data-tab="community">
        <h3 className="font-bold mb-1">Verified Badge Icon</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Shown next to names in Partners in Mission and beside your points count in the header.
          Upload an image to replace the default gold cross — change it any time, takes effect instantly.
        </p>
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 rounded-full bg-neutral-900 border border-neutral-800 flex items-center justify-center overflow-hidden shrink-0">
            {badgeIconUrl ? (
              <img src={badgeIconUrl} className="w-full h-full object-cover" />
            ) : (
              <span className="text-xl">✝️</span>
            )}
          </div>
          <div>
            <input ref={badgeFileRef} type="file" accept="image/*" className="hidden" onChange={handleBadgeUpload} />
            <button
              type="button"
              onClick={() => badgeFileRef.current?.click()}
              disabled={uploadingBadge}
              className="btn-secondary px-4 py-2 text-sm"
            >
              {uploadingBadge ? "Uploading..." : "Upload Icon"}
            </button>
            {badgeIconUrl && (
              <button
                type="button"
                onClick={() => setBadgeIconUrl("")}
                className="ml-2 text-xs text-neutral-500 hover:text-red-500"
              >
                Reset to default
              </button>
            )}
          </div>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "community" ? "" : "hidden"}`} data-tab="community">
        <h3 className="font-bold mb-1">Community Stats Starting Numbers</h3>
        <p className="text-xs text-neutral-500 mb-4">
          The "requests shared" and "prayers lifted" counters on the Community page are real —
          they're your actual post count and actual prayer-reaction count, plus this starting number
          added on top (so a brand-new site doesn't show 1 or 2). Every increase from here on is 100%
          real activity.
        </p>
        <div className="grid sm:grid-cols-2 gap-3">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Requests shared — starting number</label>
            <input
              type="number"
              min="0"
              value={communityRequestBase}
              onChange={(e) => setCommunityRequestBase(parseInt(e.target.value) || 0)}
              className={inputCls}
            />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Prayers lifted — starting number</label>
            <input
              type="number"
              min="0"
              value={communityPrayerBase}
              onChange={(e) => setCommunityPrayerBase(parseInt(e.target.value) || 0)}
              className={inputCls}
            />
          </div>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "community" ? "" : "hidden"}`} data-tab="community">
        <h3 className="font-bold mb-1">Supporter Badge Display</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Controls the badge icon shown next to names in the Partners in Mission list. Set how many
          cross badges show based on the gift amount range.
        </p>
        <div className="mb-4">
          <label className="block text-xs text-neutral-500 mb-1.5">Badge size (px)</label>
          <input type="number" min="8" max="40" value={supporterBadgeSize} onChange={(e) => setSupporterBadgeSize(parseInt(e.target.value) || 13)} className={`${inputCls} max-w-[150px]`} />
        </div>

        <label className="block text-xs text-neutral-500 mb-2">Amount ranges</label>
        <div className="space-y-2 mb-3">
          {badgeTiers.map((t, i) => (
            <div key={i} className="flex items-center gap-2">
              <span className="text-xs text-neutral-500">$</span>
              <input
                type="number" min="0" value={t.min}
                onChange={(e) => setBadgeTiers((arr) => arr.map((row, idx) => idx === i ? { ...row, min: parseFloat(e.target.value) || 0 } : row))}
                className={`${inputCls} w-20`}
              />
              <span className="text-xs text-neutral-500">to</span>
              <input
                type="number" min="0" value={t.max ?? ""} placeholder="∞"
                onChange={(e) => setBadgeTiers((arr) => arr.map((row, idx) => idx === i ? { ...row, max: e.target.value ? parseFloat(e.target.value) : null } : row))}
                className={`${inputCls} w-20`}
              />
              <span className="text-xs text-neutral-500">=</span>
              <input
                type="number" min="1" value={t.crosses}
                onChange={(e) => setBadgeTiers((arr) => arr.map((row, idx) => idx === i ? { ...row, crosses: parseInt(e.target.value) || 1 } : row))}
                className={`${inputCls} w-16`}
              />
              <span className="text-xs text-neutral-500">cross{t.crosses === 1 ? "" : "es"}</span>
              <button onClick={() => setBadgeTiers((arr) => arr.filter((_, idx) => idx !== i))} className="text-neutral-600 hover:text-red-500 text-xs ml-auto">
                Remove
              </button>
            </div>
          ))}
        </div>
        <button
          onClick={() => setBadgeTiers((arr) => [...arr, { min: 0, max: null, crosses: 1 }])}
          className="btn-secondary px-3 py-1.5 text-xs"
        >
          + Add Range
        </button>
        <p className="text-xs text-neutral-600 mt-3">
          Leave "to" blank for no upper limit (e.g. "100 to ∞ = 3 crosses" means $100 and above).
        </p>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "general" ? "" : "hidden"}`} data-tab="general">
        <h3 className="font-bold mb-1">Default Text Size (F- / F / F+)</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Which size new visitors see by default, before they adjust it themselves using the header
          controls. Anyone who's already picked their own size keeps their choice.
        </p>
        <select
          value={defaultFontScaleIndex}
          onChange={(e) => setDefaultFontScaleIndex(parseInt(e.target.value))}
          className={`${inputCls} max-w-[200px]`}
        >
          <option value={0}>F- (small)</option>
          <option value={1}>F (default, 130%)</option>
          <option value={2}>F+ (large)</option>
        </select>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "general" ? "" : "hidden"}`} data-tab="general">
        <h3 className="font-bold mb-1">Upload Size Limits</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Applies to community post attachments, avatars, covers, and welcome animation media.
        </p>
        <div className="grid sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Max image size (MB)</label>
            <input type="number" min="0.5" step="0.5" value={maxImageMb} onChange={(e) => setMaxImageMb(parseFloat(e.target.value) || 10)} className={inputCls} />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Max video size (MB)</label>
            <input type="number" min="0.5" step="1" value={maxVideoMb} onChange={(e) => setMaxVideoMb(parseFloat(e.target.value) || 100)} className={inputCls} />
          </div>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "community" ? "" : "hidden"}`} data-tab="community">
        <h3 className="font-bold mb-1">New Member Mission Notification</h3>
        <p className="text-xs text-neutral-500 mb-4">
          When someone registers, let them know about any missions/targets that are already active
          (they'd have missed the original announcement since they weren't a member yet).
        </p>
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={notifyNewMembersOfMissions} onChange={(e) => setNotifyNewMembersOfMissions(e.target.checked)} />
          Notify new members about currently active missions
        </label>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "payments" ? "" : "hidden"}`} data-tab="payments">
        <h3 className="font-bold mb-1">Free Ebook for New Members</h3>
        <p className="text-xs text-neutral-500 mb-4">
          When someone subscribes to any paid plan, they'll get an email offering this ebook free —
          it only appears in their library once they click to confirm. Leave blank to disable.
        </p>
        <select value={freeEbookProductId} onChange={(e) => setFreeEbookProductId(e.target.value)} className={inputCls}>
          <option value="">— None (disabled) —</option>
          {digitalProducts.map((p) => (
            <option key={p.id} value={p.id}>{p.title}</option>
          ))}
        </select>
        {digitalProducts.length === 0 && (
          <p className="text-xs text-neutral-600 mt-2">
            No digital products yet — create one in <a href="/admin/products" className="text-red-500">Shop Products</a> first.
          </p>
        )}
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "tips" ? "" : "hidden"}`} data-tab="tips">
        <h3 className="font-bold mb-1">Short Link to Tips Page</h3>
        <p className="text-xs text-neutral-500 mb-4">
          A clean, short link you can share anywhere — doesn't say "tips" in the URL. Letters/numbers/hyphens only.
        </p>
        <div className="flex items-center gap-2">
          <span className="text-sm text-neutral-500 whitespace-nowrap">yoursite.com/</span>
          <input
            value={tipShortLinkSlug}
            onChange={(e) => setTipShortLinkSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""))}
            className={inputCls}
          />
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "tips" ? "" : "hidden"}`} data-tab="tips">
        <h3 className="font-bold mb-1">Tip Amount Buttons</h3>
        <p className="text-xs text-neutral-500 mb-4">
          The preset amount buttons shown on the tips page — shown 3 per row, wrapping to as many
          rows as you add. Add an emoji to show in front of the value (purely visual, doesn't affect
          the donation amount) — leave blank for none.
        </p>
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 mb-3">
          {tipPresetAmounts.map((b, i) => (
            <div key={i} className="flex items-center gap-1">
              <input
                placeholder="🙏"
                value={b.emoji}
                maxLength={4}
                onChange={(e) =>
                  setTipPresetAmounts((prev) => prev.map((x, idx) => (idx === i ? { ...x, emoji: e.target.value } : x)))
                }
                className={`${inputCls} !py-1.5 !w-12 text-center shrink-0`}
              />
              <span className="text-neutral-500 text-sm">$</span>
              <input
                type="number"
                min="1"
                value={b.amount}
                onChange={(e) =>
                  setTipPresetAmounts((prev) => prev.map((x, idx) => (idx === i ? { ...x, amount: parseFloat(e.target.value) || 0 } : x)))
                }
                className={`${inputCls} !py-1.5`}
              />
              <button
                onClick={() => setTipPresetAmounts((prev) => prev.filter((_, idx) => idx !== i))}
                title="Remove this button"
                className="text-neutral-600 hover:text-red-500 shrink-0 px-1"
              >
                ✕
              </button>
            </div>
          ))}
        </div>
        <button
          onClick={() => setTipPresetAmounts((prev) => [...prev, { amount: 10, emoji: "" }])}
          className="btn-secondary px-3 py-1.5 text-xs"
        >
          + Add Button
        </button>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "tips" ? "" : "hidden"}`} data-tab="tips">
        <div className="flex items-center justify-between mb-1">
          <h3 className="font-bold">Humble Giver Box</h3>
          <label className="flex items-center gap-2 text-xs">
            <input type="checkbox" checked={tipHumbleEnabled} onChange={(e) => setTipHumbleEnabled(e.target.checked)} />
            Show on tips page
          </label>
        </div>
        <p className="text-xs text-neutral-500 mb-3">
          A small, single-button box for people who want to give a modest amount without feeling
          out of place next to the bigger numbers. Same click animation as the box above.
        </p>
        <label className="block text-xs text-neutral-500 mb-1.5">Title</label>
        <input value={tipHumbleTitle} onChange={(e) => setTipHumbleTitle(e.target.value)} className={`${inputCls} mb-3`} />
        <label className="block text-xs text-neutral-500 mb-1.5">Amount</label>
        <div className="flex items-center gap-1 w-32">
          <span className="text-neutral-500 text-sm">$</span>
          <input
            type="number"
            min="1"
            value={tipHumbleAmount}
            onChange={(e) => setTipHumbleAmount(parseFloat(e.target.value) || 0)}
            className={`${inputCls} !py-1.5`}
          />
        </div>
      </div>

      <div className={`card p-5 mt-6 border-amber-800/50 bg-amber-950/10 ${activeTab === "tips" ? "" : "hidden"}`} data-tab="tips">
        <h3 className="font-bold mb-1 text-amber-400">Special VIP Donators — Amount Buttons</h3>
        <div className="mb-3">
          <label className="block text-xs text-neutral-500 mb-1.5">Box title</label>
          <input value={tipVipBoxTitle} onChange={(e) => setTipVipBoxTitle(e.target.value)} className={inputCls} />
        </div>
        <p className="text-xs text-neutral-500 mb-4">
          A second, higher-tier set of donation buttons shown below the normal ones. No custom/"Other"
          option here — only these exact preset amounts. A visitor can pick from either box, but not both.
        </p>
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 mb-3">
          {tipVipPresetAmounts.map((b, i) => (
            <div key={i} className="flex items-center gap-1">
              <input
                placeholder="👑"
                value={b.emoji}
                maxLength={4}
                onChange={(e) =>
                  setTipVipPresetAmounts((prev) => prev.map((x, idx) => (idx === i ? { ...x, emoji: e.target.value } : x)))
                }
                className={`${inputCls} !py-1.5 !w-12 text-center shrink-0`}
              />
              <span className="text-neutral-500 text-sm">$</span>
              <input
                type="number"
                min="1"
                value={b.amount}
                onChange={(e) =>
                  setTipVipPresetAmounts((prev) => prev.map((x, idx) => (idx === i ? { ...x, amount: parseFloat(e.target.value) || 0 } : x)))
                }
                className={`${inputCls} !py-1.5`}
              />
              <button
                onClick={() => setTipVipPresetAmounts((prev) => prev.filter((_, idx) => idx !== i))}
                title="Remove this button"
                className="text-neutral-600 hover:text-red-500 shrink-0 px-1"
              >
                ✕
              </button>
            </div>
          ))}
        </div>
        <button
          onClick={() => setTipVipPresetAmounts((prev) => [...prev, { amount: 500, emoji: "" }])}
          className="btn-secondary px-3 py-1.5 text-xs"
        >
          + Add VIP Button
        </button>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "tips" ? "" : "hidden"}`} data-tab="tips">
        <h3 className="font-bold mb-1">Button Click Sounds</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Optional — plays when someone clicks an amount button. If you don't upload a sound for a box,
          clicking it just stays silent (no default sound is used).
        </p>
        <div className="grid sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Normal buttons sound</label>
            {tipNormalClickSound && (
              <audio controls src={tipNormalClickSound} className="w-full mb-2 h-9" />
            )}
            <input
              type="file"
              accept="audio/*"
              disabled={uploadingNormalSound}
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                setUploadingNormalSound(true);
                const formData = new FormData();
                formData.append("file", file);
                const res = await fetch("/api/upload", { method: "POST", body: formData });
                const data = await res.json();
                setUploadingNormalSound(false);
                if (res.ok) setTipNormalClickSound(data.url);
                else alert(data.error || "Upload failed.");
              }}
              className="text-xs"
            />
            {uploadingNormalSound && <p className="text-xs text-neutral-500 mt-1">Uploading...</p>}
            {tipNormalClickSound && (
              <button onClick={() => setTipNormalClickSound("")} className="text-xs text-red-500 mt-1 block">
                Remove sound
              </button>
            )}
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">VIP buttons sound</label>
            {tipVipClickSound && (
              <audio controls src={tipVipClickSound} className="w-full mb-2 h-9" />
            )}
            <input
              type="file"
              accept="audio/*"
              disabled={uploadingVipSound}
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                setUploadingVipSound(true);
                const formData = new FormData();
                formData.append("file", file);
                const res = await fetch("/api/upload", { method: "POST", body: formData });
                const data = await res.json();
                setUploadingVipSound(false);
                if (res.ok) setTipVipClickSound(data.url);
                else alert(data.error || "Upload failed.");
              }}
              className="text-xs"
            />
            {uploadingVipSound && <p className="text-xs text-neutral-500 mt-1">Uploading...</p>}
            {tipVipClickSound && (
              <button onClick={() => setTipVipClickSound("")} className="text-xs text-red-500 mt-1 block">
                Remove sound
              </button>
            )}
          </div>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "tips" ? "" : "hidden"}`} data-tab="tips">
        <h3 className="font-bold mb-1">Click Animation</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Every button click shows a brief celebration. By default that's an animated sparkle/snow burst —
          upload a GIF below to replace it for that box instead. It shows centered on screen for the
          duration set here, then disappears automatically.
        </p>
        <div className="mb-4">
          <label className="block text-xs text-neutral-500 mb-1.5">Popup duration (seconds)</label>
          <input
            type="number"
            min="0.5"
            step="0.5"
            value={tipPopupDurationSeconds}
            onChange={(e) => setTipPopupDurationSeconds(parseFloat(e.target.value) || 2)}
            className={`${inputCls} !w-24`}
          />
        </div>
        <div className="grid sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Normal buttons GIF (optional)</label>
            {tipNormalPopupGif && <img src={tipNormalPopupGif} alt="" className="h-20 rounded mb-2" />}
            <input
              type="file"
              accept="image/gif,image/*"
              disabled={uploadingNormalGif}
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                setUploadingNormalGif(true);
                const formData = new FormData();
                formData.append("file", file);
                const res = await fetch("/api/upload", { method: "POST", body: formData });
                const data = await res.json();
                setUploadingNormalGif(false);
                if (res.ok) setTipNormalPopupGif(data.url);
                else alert(data.error || "Upload failed.");
              }}
              className="text-xs"
            />
            {uploadingNormalGif && <p className="text-xs text-neutral-500 mt-1">Uploading...</p>}
            {tipNormalPopupGif && (
              <>
                <button onClick={() => setTipNormalPopupGif("")} className="text-xs text-red-500 mt-1 block">
                  Remove GIF (use default sparkle animation)
                </button>
                <label className="block text-xs text-neutral-500 mt-2 mb-1">
                  This GIF's real length (seconds) — caps display time, won't stay open longer than this
                </label>
                <input
                  type="number"
                  min="0.5"
                  step="0.5"
                  placeholder="e.g. 2"
                  value={tipNormalGifLength}
                  onChange={(e) => setTipNormalGifLength(e.target.value)}
                  className={`${inputCls} !w-24 !py-1.5`}
                />
              </>
            )}
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">VIP buttons GIF (optional)</label>
            {tipVipPopupGif && <img src={tipVipPopupGif} alt="" className="h-20 rounded mb-2" />}
            <input
              type="file"
              accept="image/gif,image/*"
              disabled={uploadingVipGif}
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                setUploadingVipGif(true);
                const formData = new FormData();
                formData.append("file", file);
                const res = await fetch("/api/upload", { method: "POST", body: formData });
                const data = await res.json();
                setUploadingVipGif(false);
                if (res.ok) setTipVipPopupGif(data.url);
                else alert(data.error || "Upload failed.");
              }}
              className="text-xs"
            />
            {uploadingVipGif && <p className="text-xs text-neutral-500 mt-1">Uploading...</p>}
            {tipVipPopupGif && (
              <>
                <button onClick={() => setTipVipPopupGif("")} className="text-xs text-red-500 mt-1 block">
                  Remove GIF (use default sparkle animation)
                </button>
                <label className="block text-xs text-neutral-500 mt-2 mb-1">
                  This GIF's real length (seconds) — caps display time, won't stay open longer than this
                </label>
                <input
                  type="number"
                  min="0.5"
                  step="0.5"
                  placeholder="e.g. 2"
                  value={tipVipGifLength}
                  onChange={(e) => setTipVipGifLength(e.target.value)}
                  className={`${inputCls} !w-24 !py-1.5`}
                />
              </>
            )}
          </div>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "tips" ? "" : "hidden"}`} data-tab="tips">
        <h3 className="font-bold mb-1">Tip Payment Success Celebration</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Shown once, right when someone's donation is confirmed. Same GIF-length capping logic applies.
        </p>
        <div className="mb-4">
          <label className="block text-xs text-neutral-500 mb-1.5">Max display duration (seconds)</label>
          <input
            type="number"
            min="0.5"
            step="0.5"
            value={tipSuccessDurationSeconds}
            onChange={(e) => setTipSuccessDurationSeconds(parseFloat(e.target.value) || 3)}
            className={`${inputCls} !w-24`}
          />
        </div>
        <div className="grid sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">GIF (optional)</label>
            {tipSuccessGif && <img src={tipSuccessGif} alt="" className="h-20 rounded mb-2" />}
            <input
              type="file"
              accept="image/gif,image/*"
              disabled={uploadingSuccessGif}
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                setUploadingSuccessGif(true);
                const formData = new FormData();
                formData.append("file", file);
                const res = await fetch("/api/upload", { method: "POST", body: formData });
                const data = await res.json();
                setUploadingSuccessGif(false);
                if (res.ok) setTipSuccessGif(data.url);
                else alert(data.error || "Upload failed.");
              }}
              className="text-xs"
            />
            {uploadingSuccessGif && <p className="text-xs text-neutral-500 mt-1">Uploading...</p>}
            {tipSuccessGif && (
              <>
                <button onClick={() => setTipSuccessGif("")} className="text-xs text-red-500 mt-1 block">
                  Remove GIF (use default sparkle animation)
                </button>
                <label className="block text-xs text-neutral-500 mt-2 mb-1">GIF's real length (seconds)</label>
                <input
                  type="number" min="0.5" step="0.5" placeholder="e.g. 3"
                  value={tipSuccessGifLength}
                  onChange={(e) => setTipSuccessGifLength(e.target.value)}
                  className={`${inputCls} !w-24 !py-1.5`}
                />
              </>
            )}
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Sound (optional)</label>
            {tipSuccessSound && <audio controls src={tipSuccessSound} className="w-full mb-2 h-9" />}
            <input
              type="file"
              accept="audio/*"
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                const formData = new FormData();
                formData.append("file", file);
                const res = await fetch("/api/upload", { method: "POST", body: formData });
                const data = await res.json();
                if (res.ok) setTipSuccessSound(data.url);
                else alert(data.error || "Upload failed.");
              }}
              className="text-xs"
            />
            {tipSuccessSound && (
              <button onClick={() => setTipSuccessSound("")} className="text-xs text-red-500 mt-1 block">
                Remove sound
              </button>
            )}
          </div>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "payments" ? "" : "hidden"}`} data-tab="payments">
        <h3 className="font-bold mb-1">Membership / Purchase Success Celebration</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Shown once when a member's plan upgrade or shop purchase is confirmed (on My Library). Same
          GIF-length capping logic applies.
        </p>
        <div className="mb-4">
          <label className="block text-xs text-neutral-500 mb-1.5">Max display duration (seconds)</label>
          <input
            type="number"
            min="0.5"
            step="0.5"
            value={upgradeSuccessDurationSeconds}
            onChange={(e) => setUpgradeSuccessDurationSeconds(parseFloat(e.target.value) || 3)}
            className={`${inputCls} !w-24`}
          />
        </div>
        <div className="grid sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">GIF (optional)</label>
            {upgradeSuccessGif && <img src={upgradeSuccessGif} alt="" className="h-20 rounded mb-2" />}
            <input
              type="file"
              accept="image/gif,image/*"
              disabled={uploadingUpgradeGif}
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                setUploadingUpgradeGif(true);
                const formData = new FormData();
                formData.append("file", file);
                const res = await fetch("/api/upload", { method: "POST", body: formData });
                const data = await res.json();
                setUploadingUpgradeGif(false);
                if (res.ok) setUpgradeSuccessGif(data.url);
                else alert(data.error || "Upload failed.");
              }}
              className="text-xs"
            />
            {uploadingUpgradeGif && <p className="text-xs text-neutral-500 mt-1">Uploading...</p>}
            {upgradeSuccessGif && (
              <>
                <button onClick={() => setUpgradeSuccessGif("")} className="text-xs text-red-500 mt-1 block">
                  Remove GIF (use default sparkle animation)
                </button>
                <label className="block text-xs text-neutral-500 mt-2 mb-1">GIF's real length (seconds)</label>
                <input
                  type="number" min="0.5" step="0.5" placeholder="e.g. 3"
                  value={upgradeSuccessGifLength}
                  onChange={(e) => setUpgradeSuccessGifLength(e.target.value)}
                  className={`${inputCls} !w-24 !py-1.5`}
                />
              </>
            )}
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Sound (optional)</label>
            {upgradeSuccessSound && <audio controls src={upgradeSuccessSound} className="w-full mb-2 h-9" />}
            <input
              type="file"
              accept="audio/*"
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                const formData = new FormData();
                formData.append("file", file);
                const res = await fetch("/api/upload", { method: "POST", body: formData });
                const data = await res.json();
                if (res.ok) setUpgradeSuccessSound(data.url);
                else alert(data.error || "Upload failed.");
              }}
              className="text-xs"
            />
            {upgradeSuccessSound && (
              <button onClick={() => setUpgradeSuccessSound("")} className="text-xs text-red-500 mt-1 block">
                Remove sound
              </button>
            )}
          </div>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "tips" ? "" : "hidden"}`} data-tab="tips">
        <h3 className="font-bold mb-1">Tip Page "Other" Button Label</h3>
        <p className="text-xs text-neutral-500 mb-4">
          The button that lets someone type a custom support amount — change its text if "Other"
          doesn't fit your style (e.g. "Custom Amount", "Choose My Own").
        </p>
        <input value={tipOtherLabel} onChange={(e) => setTipOtherLabel(e.target.value)} className={inputCls} />
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "pages" ? "" : "hidden"}`} data-tab="pages">
        <h3 className="font-bold mb-1">Company Attribution</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Shown in the footer as "© {new Date().getFullYear()} [Company]. All rights reserved." Leave blank to
          just show your site name instead. If you add a URL, the company name becomes a clickable link (e.g. to
          your parent company's website).
        </p>
        <div className="space-y-3">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Company name</label>
            <input
              value={companyName}
              onChange={(e) => setCompanyName(e.target.value)}
              placeholder="Your Company LLC"
              className={inputCls}
            />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Company website (opens when the name is clicked)</label>
            <input
              value={companyUrl}
              onChange={(e) => setCompanyUrl(e.target.value)}
              placeholder="https://yourcompany.com"
              className={inputCls}
            />
          </div>
        </div>
      </div>

      <div className={`card p-5 mt-6 ${activeTab === "pages" ? "" : "hidden"}`} data-tab="pages">
        <h3 className="font-bold mb-1">Footer Pages</h3>
        <p className="text-xs text-neutral-500 mb-4">
          Edit the text shown on each footer page. Start a line with <code className="bg-neutral-900 px-1 rounded">## </code>
          to make it a subheading, and leave a blank line between paragraphs. Use <code className="bg-neutral-900 px-1 rounded">{"{{siteName}}"}</code>{" "}
          anywhere you want your site name inserted automatically. Leave a box empty to use the built-in default text.
        </p>
        <div className="space-y-5">
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">About page</label>
            <textarea
              value={pageAboutContent}
              onChange={(e) => setPageAboutContent(e.target.value)}
              rows={6}
              className={textareaCls}
            />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Contact page</label>
            <textarea
              value={pageContactContent}
              onChange={(e) => setPageContactContent(e.target.value)}
              rows={6}
              className={textareaCls}
            />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Terms and Conditions</label>
            <textarea
              value={pageTermsContent}
              onChange={(e) => setPageTermsContent(e.target.value)}
              rows={6}
              className={textareaCls}
            />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Privacy Policy</label>
            <textarea
              value={pagePrivacyContent}
              onChange={(e) => setPagePrivacyContent(e.target.value)}
              rows={6}
              className={textareaCls}
            />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1.5">Refund Policy</label>
            <textarea
              value={pageRefundContent}
              onChange={(e) => setPageRefundContent(e.target.value)}
              rows={6}
              className={textareaCls}
            />
          </div>
        </div>
      </div>

      <div className="card p-5 mt-6">
        <div className="flex items-center gap-3">
          <button onClick={save} disabled={saving} className="btn-primary px-5 py-2 text-sm">
            {saving ? "Saving..." : "Save Settings"}
          </button>
          {saved && <span className="text-green-500 text-sm">✓ Saved — refresh the site to see changes</span>}
        </div>
      </div>
    </div>
  );
}
