/* eslint-disable */
// Gift Registry — admin view with publish controls + public-side purchase sync

const STORAGE_KEY = "jagdevhub_public_registry";

const ADMIN_SEED = [
  { id: 1, person: "Mom",   occasion: "Birthday",    itemName: "Garden tools set",           priceRange: "$40–$60",   link: "https://example.com", notes: "She mentioned hers were getting rusty.", published: true,  purchased: false, purchasedBy: null },
  { id: 2, person: "Dad",   occasion: "Father's Day", itemName: "Leather wallet",             priceRange: "$80–$120",  link: null,                  notes: null,                                   published: true,  purchased: true,  purchasedBy: "Priya" },
  { id: 3, person: "Priya", occasion: "Birthday",    itemName: "Noise-cancelling headphones", priceRange: "$200–$300", link: "https://example.com", notes: null,                                   published: true,  purchased: false, purchasedBy: null },
  { id: 4, person: "Arjun", occasion: "Graduation",  itemName: "Travel backpack",             priceRange: "$60–$90",   link: null,                  notes: "He's been eyeing the Osprey one.",     published: true,  purchased: false, purchasedBy: null },
  { id: 5, person: "Mom",   occasion: "Mother's Day",itemName: "Cookbook subscription",       priceRange: "$30",       link: "https://example.com", notes: null,                                   published: false, purchased: false, purchasedBy: null },
  { id: 6, person: "Nani",  occasion: "Anniversary", itemName: "Photo album",                 priceRange: "$25",       link: null,                  notes: "Print the Goa photos.",                published: false, purchased: false, purchasedBy: null },
];

// Load items from storage
function loadItems() {
  return Storage.getArray('familyhub_registry', 'items');
}

async function publishToStorage(items) {
  const toPublish = items.filter(i => i.published);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(toPublish));

  const db = window._db;
  if (!db) return;
  try {
    const col = db.collection("public_registry");
    const existing = await col.get();
    const batch = db.batch();
    existing.forEach(doc => batch.delete(doc.ref));
    toPublish.forEach(item => {
      batch.set(col.doc(String(item.id)), {
        id: item.id,
        person: item.person || "",
        occasion: item.occasion || "",
        itemName: item.itemName || "",
        priceRange: item.priceRange || null,
        link: item.link || null,
        notes: item.notes || null,
        purchased: item.purchased || false,
        purchasedBy: item.purchasedBy || null,
        published: true,
        publishedAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
    });
    await batch.commit();
  } catch (err) {
    console.error("Firestore publish failed:", err);
  }
}

// ── Sub-components ───────────────────────────────────────────────────────────

const PublishBanner = ({ published, itemCount, publicUrl, onPublish, onCopy, copied }) => (
  <div className={
    "rounded-lg p-4 mb-6 " +
    (published
      ? "bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800"
      : "bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800")
  }>
    <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3">
      <div className="flex-1 min-w-0">
        {published ? (
          <p className="text-sm font-semibold text-green-800 dark:text-green-200 mb-1">
            ✓ Registry published · {itemCount} items visible to guests
          </p>
        ) : (
          <p className="text-sm font-semibold text-blue-800 dark:text-blue-200 mb-1">
            Registry not yet published. Guests can't see it yet.
          </p>
        )}
        <p className="text-xs text-gray-500 dark:text-gray-400">
          Toggle individual items with the 👁️ eye icon · publish when ready
        </p>

        {/* URL display */}
        {published && (
          <div className="mt-3 flex items-center gap-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg px-3 py-2 max-w-full overflow-hidden">
            <span className="text-gray-400 text-xs shrink-0">🔗</span>
            <span className="text-xs font-mono text-gray-600 dark:text-gray-300 truncate flex-1">{publicUrl}</span>
          </div>
        )}

        {/* Where it lives */}
        {published && (
          <p className="text-xs text-gray-400 dark:text-gray-500 mt-2">
            Hosted at your Cloudflare Pages root — publicly accessible, no login required.
          </p>
        )}
      </div>

      <div className="flex gap-2 shrink-0">
        {published && (
          <button
            onClick={onCopy}
            className={
              "px-4 py-2 rounded-lg text-sm font-semibold transition-colors " +
              (copied
                ? "bg-green-600 text-white"
                : "bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600")
            }
          >
            {copied ? "✓ Copied!" : "🔗 Copy link"}
          </button>
        )}
        <BtnPrimary onClick={onPublish}>
          {published ? "Update registry" : "📤 Publish registry"}
        </BtnPrimary>
      </div>
    </div>
  </div>
);

const AdminGiftCard = ({ item, onTogglePurchased, onTogglePublished, onDelete, onEdit }) => (
  <div className={
    "bg-white dark:bg-gray-800 rounded-lg shadow-md p-5 transition-all duration-200 " +
    (item.published ? "ring-1 ring-blue-200 dark:ring-blue-800" : "opacity-60")
  }>
    {/* Header row */}
    <div className="flex justify-between items-start mb-3 gap-2">
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-1 flex-wrap">
          <span className="text-xs font-semibold text-gray-500 dark:text-gray-400">{item.person}</span>
          <span className="text-xs text-gray-400 dark:text-gray-500">·</span>
          <span className="text-xs text-gray-500 dark:text-gray-400">{item.occasion}</span>
        </div>
        <h3 className="text-base font-bold text-gray-900 dark:text-white leading-snug">{item.itemName}</h3>
      </div>
      <div className="flex items-center gap-1 shrink-0">
        {/* Publish toggle */}
        <button
          onClick={() => onTogglePublished(item.id)}
          title={item.published ? "Hide from public" : "Include in public registry"}
          className={
            "p-1.5 rounded-lg transition-colors text-base " +
            (item.published
              ? "text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/30"
              : "text-gray-400 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700")
          }
        >
          {item.published ? "👁️" : "🙈"}
        </button>
        <Pill tone={item.purchased ? "success" : "info"}>
          {item.purchased ? "✓ Purchased" : "Available"}
        </Pill>
      </div>
    </div>

    {/* Details */}
    {item.priceRange && <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">💰 {item.priceRange}</p>}
    {item.link && (
      <a href={item.link} target="_blank" rel="noreferrer"
        className="text-blue-600 dark:text-blue-400 hover:underline text-sm mb-1 inline-block">View item →</a>
    )}
    {item.notes && <p className="text-sm text-gray-600 dark:text-gray-400 italic mt-1">Notes: {item.notes}</p>}

    {/* Purchase info */}
    {item.purchased && item.purchasedBy && (
      <div className="mt-2 flex items-center gap-2">
        <span className="text-xs bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 px-2 py-0.5 rounded-full font-medium">
          Marked by {item.purchasedBy}
        </span>
      </div>
    )}

    {/* Actions */}
    <div className="flex gap-3 mt-3 pt-3 border-t border-gray-100 dark:border-gray-700 text-sm">
      <button onClick={() => onTogglePurchased(item.id)}
        className="text-green-600 dark:text-green-400 hover:underline">
        {item.purchased ? "Undo purchase" : "Mark purchased"}
      </button>
      <button onClick={() => onEdit(item)} className="text-blue-600 dark:text-blue-400 hover:underline">Edit</button>
      <button onClick={() => onDelete(item.id)} className="text-red-600 dark:text-red-400 hover:underline">Delete</button>
    </div>
  </div>
);

// ── Main component ───────────────────────────────────────────────────────────

const GiftRegistryScreen = () => {
  const [items, setItems] = React.useState(() => {
    const stored = Storage.getArray('familyhub_registry', 'items');
    return stored;
  });
  const [filter, setFilter]     = React.useState("all");
  const [published, setPublished] = React.useState(() => !!localStorage.getItem(STORAGE_KEY));
  const [copied, setCopied]     = React.useState(false);
  const [showAdd, setShowAdd]   = React.useState(false);
  const [draft, setDraft]       = React.useState({ person: "", occasion: "", itemName: "", priceRange: "", link: "", notes: "" });

  const saveItems = (newItems) => { setItems(newItems); Storage.set('familyhub_registry', { items: newItems }); };
  const addItem = () => {
    if (!draft.itemName.trim()) return;
    const updated = [...items, { id: Date.now(), ...draft, published: false, purchased: false, purchasedBy: null }];
    saveItems(updated);
    setDraft({ person: "", occasion: "", itemName: "", priceRange: "", link: "", notes: "" });
    setShowAdd(false);
  };

  const togglePurchased = (id) => {
    const updated = items.map(i => i.id === id ? { ...i, purchased: !i.purchased, purchasedBy: !i.purchased ? "Admin" : null } : i);
    saveItems(updated);
  };

  const togglePublished = (id) => {
    const updated = items.map(i => i.id === id ? { ...i, published: !i.published } : i);
    saveItems(updated);
  };

  const deleteItem = (id) => { if (!window.confirm("Are you sure you want to delete this gift idea?")) return; const updated = items.filter(i => i.id !== id); saveItems(updated); };
  const [editGift, setEditGift] = React.useState(null);
  const startEditGift = (item) => { setEditGift({ ...item }); };
  const saveEditGift = () => {
    if (!editGift.itemName.trim() || !editGift.person.trim()) return;
    const updated = items.map(i => i.id === editGift.id ? { ...i, person: editGift.person.trim(), occasion: editGift.occasion || null, itemName: editGift.itemName.trim(), priceRange: editGift.priceRange || null, link: editGift.link || null, notes: editGift.notes || null } : i);
    saveItems(updated);
    setEditGift(null);
  };

  const [publishing, setPublishing] = React.useState(false);
  const publish = async () => {
    const pubCount = items.filter(i => i.published).length;
    if (!confirm("Publish " + pubCount + " item" + (pubCount !== 1 ? "s" : "") + " to the public registry? Guests will be able to see them.")) return;
    setPublishing(true);
    await publishToStorage(items);
    setPublished(true);
    setPublishing(false);
    alert("Registry published! " + pubCount + " item" + (pubCount !== 1 ? "s" : "") + " are now visible to guests.");
  };

  // In production this lives at the Cloudflare Pages root — outside Zero Trust
  const PUBLIC_URL = "https://family-hub-1jb.pages.dev/public-registry";

  const copyLink = () => {
    navigator.clipboard?.writeText(PUBLIC_URL).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const publishedItems = items.filter(i => i.published);

  const filtered = items.filter(i =>
    filter === "all"         ? true :
    filter === "published"   ? i.published :
    filter === "purchased"   ? i.purchased :
    !i.purchased
  );

  const Tab = ({ id, label, count }) => (
    <button
      onClick={() => setFilter(id)}
      className={
        "px-4 py-2 border-b-2 transition-colors whitespace-nowrap " +
        (filter === id
          ? "border-blue-500 text-blue-600 dark:text-blue-400 font-semibold"
          : "border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200")
      }
    >
      {label} ({count})
    </button>
  );

  return (
    <section className="p-4 md:p-6">
      {/* Page header */}
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-3xl font-bold text-gray-900 dark:text-white">Gift Registry</h2>
        <BtnPrimary onClick={() => setShowAdd(true)}>+ Add Gift Idea</BtnPrimary>
      </div>

      {showAdd && (
        <Modal title="Add Gift Idea" onClose={() => setShowAdd(false)} onSubmit={addItem} submitLabel="Add Gift">
          <div className="space-y-4">
            <div><Label required>Item Name</Label><Input placeholder="e.g. Garden tools set" value={draft.itemName} onChange={e => setDraft({...draft, itemName: e.target.value})} autoFocus /></div>
            <div><Label required>For (Person)</Label><Input placeholder="e.g. Mom" value={draft.person} onChange={e => setDraft({...draft, person: e.target.value})} /></div>
            <div><Label>Occasion</Label><Input placeholder="e.g. Birthday" value={draft.occasion} onChange={e => setDraft({...draft, occasion: e.target.value})} /></div>
            <div><Label>Price Range</Label><Input placeholder="e.g. $40–$60" value={draft.priceRange} onChange={e => setDraft({...draft, priceRange: e.target.value})} /></div>
            <div><Label>Link</Label><Input placeholder="https://..." value={draft.link} onChange={e => setDraft({...draft, link: e.target.value})} /></div>
            <div><Label>Notes</Label><Textarea rows={2} placeholder="Any notes..." value={draft.notes} onChange={e => setDraft({...draft, notes: e.target.value})} /></div>
          </div>
        </Modal>
      )}

      {/* Publish banner */}
      <PublishBanner
        published={published}
        itemCount={publishedItems.length}
        publicUrl={PUBLIC_URL}
        onPublish={publish}
        onCopy={copyLink}
        copied={copied}
      />

      {/* Filter tabs */}
      <div className="flex gap-1 sm:gap-4 mb-6 border-b border-gray-200 dark:border-gray-700 overflow-x-auto">
        <Tab id="all"       label="All"       count={items.length} />
        <Tab id="published" label="Published" count={publishedItems.length} />
        <Tab id="unpurchased" label="Available" count={items.filter(i => !i.purchased).length} />
        <Tab id="purchased" label="Purchased" count={items.filter(i => i.purchased).length} />
      </div>

      {/* Grid */}
      <div className="grid md:grid-cols-2 gap-5">
        {filtered.length === 0 && (
          <p className="col-span-2 text-center text-gray-500 dark:text-gray-400 py-12">
            No gift ideas here yet. Add one to get started!
          </p>
        )}
        {filtered.map(item => (
          <AdminGiftCard
            key={item.id}
            item={item}
            onTogglePurchased={togglePurchased}
            onTogglePublished={togglePublished}
            onDelete={deleteItem}
            onEdit={startEditGift}
          />
        ))}
      </div>

      {editGift && (
        <Modal title="Edit Gift Idea" onClose={() => setEditGift(null)} onSubmit={saveEditGift} submitLabel="Save">
          <div className="space-y-4">
            <div><Label required>Item Name</Label><Input value={editGift.itemName} onChange={e => setEditGift({...editGift, itemName: e.target.value})} autoFocus /></div>
            <div><Label required>For (Person)</Label><Input value={editGift.person} onChange={e => setEditGift({...editGift, person: e.target.value})} /></div>
            <div><Label>Occasion</Label><Input value={editGift.occasion || ''} onChange={e => setEditGift({...editGift, occasion: e.target.value})} /></div>
            <div><Label>Price Range</Label><Input value={editGift.priceRange || ''} onChange={e => setEditGift({...editGift, priceRange: e.target.value})} /></div>
            <div><Label>Link</Label><Input value={editGift.link || ''} onChange={e => setEditGift({...editGift, link: e.target.value})} /></div>
            <div><Label>Notes</Label><Textarea rows={2} value={editGift.notes || ''} onChange={e => setEditGift({...editGift, notes: e.target.value})} /></div>
          </div>
        </Modal>
      )}
    </section>
  );
};

window.GiftRegistryScreen = GiftRegistryScreen;
