import React, { useEffect, useState } from "react";

/**
 * IBrandBiz — Cookie Policy + Cookie Banner
 * Framework: React + TailwindCSS
 * Deliverables in one file for easy copy/paste:
 *  1) <CookiePolicyPage /> — legal page at /cookie-policy
 *  2) <CookieConsentBanner /> — bottom banner for consent with choices
 *  3) util helpers: getConsent(), setConsent(), hasConsentCategory()
 *
 * Replace placeholders before publishing:
 *  - COMPANY_NAME, CONTACT_EMAIL, EFFECTIVE_DATE
 * Optional: wire analytics/marketing scripts to consent categories in your app root.
 */

/* ============================ Config ============================ */
const COMPANY_NAME = "IBrandBiz";
const CONTACT_EMAIL = "privacy@ibrandbiz.com"; // TODO
const EFFECTIVE_DATE = "2025-09-13"; // TODO

/* ========================= Consent Helpers ====================== */
export type ConsentState = {
  essential: true; // always true, non-optional
  analytics: boolean;
  marketing: boolean;
};

const CONSENT_KEY = "ibrandbiz.cookieConsent.v1";

export function getConsent(): ConsentState | null {
  try {
    const raw = localStorage.getItem(CONSENT_KEY);
    return raw ? (JSON.parse(raw) as ConsentState) : null;
  } catch {
    return null;
  }
}

export function setConsent(next: ConsentState) {
  localStorage.setItem(CONSENT_KEY, JSON.stringify(next));
}

export function hasConsentCategory(category: keyof ConsentState): boolean {
  const c = getConsent();
  if (!c) return false;
  return !!c[category];
}

/* ======================= Cookie Banner UI ======================= */
export function CookieConsentBanner() {
  const existing = getConsent();
  const [show, setShow] = useState(!existing);
  const [analytics, setAnalytics] = useState(true);
  const [marketing, setMarketing] = useState(false);

  useEffect(() => {
    // If consent exists, do not show banner
    setShow(!existing);
    // Optionally initialize analytics here based on existing consent
  }, []);

  const acceptAll = () => {
    setConsent({ essential: true, analytics: true, marketing: true });
    setShow(false);
    // TODO: initialize analytics/marketing scripts
  };

  const saveChoices = () => {
    setConsent({ essential: true, analytics, marketing });
    setShow(false);
    // TODO: conditionally init scripts based on choices
  };

  const rejectNonEssential = () => {
    setConsent({ essential: true, analytics: false, marketing: false });
    setShow(false);
  };

  if (!show) return null;

  return (
    <div className="fixed inset-x-0 bottom-0 z-50 border-t border-slate-200 bg-white/95 backdrop-blur">
      <div className="mx-auto max-w-6xl px-4 py-4 sm:py-5">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div className="sm:max-w-3xl">
            <h2 className="text-sm font-semibold text-[#03222e]">Cookies on {COMPANY_NAME}</h2>
            <p className="mt-1 text-xs sm:text-sm text-slate-600">
              We use essential cookies to make our site work. We’d also like to use analytics and marketing cookies to help us
              improve and show relevant content. You can change your choices anytime.
            </p>
            <div className="mt-3 flex items-center gap-6 text-sm">
              <label className="inline-flex items-center gap-2">
                <input type="checkbox" checked disabled className="h-4 w-4" />
                Essential (required)
              </label>
              <label className="inline-flex items-center gap-2">
                <input
                  type="checkbox"
                  className="h-4 w-4"
                  checked={analytics}
                  onChange={(e) => setAnalytics(e.target.checked)}
                />
                Analytics
              </label>
              <label className="inline-flex items-center gap-2">
                <input
                  type="checkbox"
                  className="h-4 w-4"
                  checked={marketing}
                  onChange={(e) => setMarketing(e.target.checked)}
                />
                Marketing
              </label>
              <a
                href="/cookie-policy"
                className="text-[#05445e] underline underline-offset-2 hover:opacity-80"
              >
                Learn more
              </a>
            </div>
          </div>

          <div className="flex shrink-0 items-center gap-2">
            <button
              onClick={rejectNonEssential}
              className="rounded-xl border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
            >
              Reject non‑essential
            </button>
            <button
              onClick={saveChoices}
              className="rounded-xl border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
            >
              Save choices
            </button>
            <button
              onClick={acceptAll}
              className="rounded-xl bg-[#189ab4] px-4 py-2 text-sm font-semibold text-white shadow hover:bg-[#05445e]"
            >
              Accept all
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ======================= Cookie Policy Page ===================== */
export default function CookiePolicyPage() {
  return (
    <main className="mx-auto max-w-4xl px-6 py-12 text-slate-800">
      <header className="mb-8">
        <p className="text-xs uppercase tracking-wider text-slate-500">Cookie Policy</p>
        <h1 className="mt-1 text-3xl font-extrabold text-[#03222e]">{COMPANY_NAME} Cookie Policy</h1>
        <p className="mt-2 text-sm text-slate-600">Effective date: {EFFECTIVE_DATE}</p>
      </header>

      <Section title="What are cookies?">
        <p>
          Cookies are small text files placed on your device by a website. They help the site function, remember preferences,
          and understand how people use the site. Similar technologies (like local storage, pixels, and beacons) are used for
          the same purposes; we refer to them collectively as “cookies.”
        </p>
      </Section>

      <Section title="How we use cookies">
        <ul className="list-disc pl-6 space-y-2">
          <li><strong>Essential:</strong> required for core functions like navigation, authentication, and security.</li>
          <li><strong>Analytics:</strong> to understand site usage and improve features and performance.</li>
          <li><strong>Marketing:</strong> to measure campaigns and show relevant content (if you opt in).</li>
        </ul>
      </Section>

      <Section title="Your choices">
        <p className="mb-2">
          On your first visit, we ask for your cookie preferences. You can update your choices anytime by clearing consent in
          your browser storage or via a future in‑app settings toggle. Essential cookies are always on because the site won’t
          work without them.
        </p>
        <p className="text-sm text-slate-600">
          Note: Disabling analytics or marketing may impact personalization and measurement features.
        </p>
      </Section>

      <Section title="Third‑party cookies">
        <p className="mb-2">
          We may use third‑party services that set cookies when enabled. Examples include analytics providers and advertising
          partners. These providers have their own privacy/cookie notices.
        </p>
      </Section>

      <Section title="Changes to this policy">
        <p>
          We may update this Cookie Policy from time to time. We will post any changes on this page and update the effective
          date above.
        </p>
      </Section>

      <Section title="Contact us">
        <p>
          Questions? Email <a className="text-[#05445e] underline" href={`mailto:${CONTACT_EMAIL}`}>{CONTACT_EMAIL}</a>.
        </p>
      </Section>
    </main>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="mt-10">
      <h2 className="text-xl font-bold text-[#03222e]">{title}</h2>
      <div className="mt-3 text-slate-700 text-[15px] leading-7">{children}</div>
    </section>
  );
}
