/* ============================================================
   FLOREA GRUP — Cookie consent (GDPR / ePrivacy, EU)
   - Banner pe prima vizita
   - Modal cu preferinte granulare (4 categorii)
   - Accept / Refuza la fel de usor (cerinta GDPR)
   - Persistenta + re-consimtamant la 180 de zile
   - Buton permanent de gestionare
   ============================================================ */
const CONSENT_KEY = "fg_cookie_consent";
const CONSENT_VERSION = 1;
const CONSENT_TTL_DAYS = 180;

function readConsent() {
  try {
    const raw = JSON.parse(localStorage.getItem(CONSENT_KEY) || "null");
    if (!raw || raw.version !== CONSENT_VERSION) return null;
    if (Date.now() - raw.ts > CONSENT_TTL_DAYS * 864e5) return null;
    return raw;
  } catch (e) { return null; }
}

/* category icons */
const CookieIc = {
  functional: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 2 4 5v6c0 5 3.4 8.5 8 11 4.6-2.5 8-6 8-11V5l-8-3z"/><path d="m9 12 2 2 4-4"/></svg>,
  preferences: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
  statistics: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 3v18h18"/><rect x="7" y="12" width="3" height="6"/><rect x="12" y="8" width="3" height="10"/><rect x="17" y="5" width="3" height="13"/></svg>,
  marketing: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="m3 11 18-5v12L3 13v-2z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg>,
  cookie: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5z"/><path d="M8.5 8.5h.01M16 15.5h.01M11.5 13.5h.01"/></svg>,
};

function CookieConsent() {
  const { L } = useL();
  const [stored, setStored] = useState(readConsent);
  const [banner, setBanner] = useState(() => !readConsent());
  const [modal, setModal] = useState(false);
  const [prefs, setPrefs] = useState(() => {
    const s = readConsent();
    return s ? s.prefs : { preferences: false, statistics: false, marketing: false };
  });

  // allow reopening from anywhere (footer link / floating button)
  useEffect(() => {
    const open = () => {
      const s = readConsent();
      setPrefs(s ? s.prefs : { preferences: false, statistics: false, marketing: false });
      setModal(true);
    };
    window.addEventListener("fg-open-cookies", open);
    return () => window.removeEventListener("fg-open-cookies", open);
  }, []);

  const persist = (p) => {
    const rec = { version: CONSENT_VERSION, ts: Date.now(), prefs: p };
    localStorage.setItem(CONSENT_KEY, JSON.stringify(rec));
    setStored(rec);
    setBanner(false);
    setModal(false);
    // expose for analytics gating (example hook)
    window.fgConsent = { functional: true, ...p };
    window.dispatchEvent(new CustomEvent("fg-consent-updated", { detail: window.fgConsent }));
  };
  const acceptAll = () => persist({ preferences: true, statistics: true, marketing: true });
  const rejectAll = () => persist({ preferences: false, statistics: false, marketing: false });
  const saveChoices = () => persist(prefs);

  const CATS = [
    { id: "functional", icon: "functional", always: true,
      name: { ro: "Funcționale", en: "Functional" },
      desc: { ro: "Necesare pentru funcționarea de bază a site-ului. Nu pot fi dezactivate.",
              en: "Required for the basic functioning of the site. Cannot be disabled." } },
    { id: "preferences", icon: "preferences",
      name: { ro: "Preferințe", en: "Preferences" },
      desc: { ro: "Rețin setările tale, precum limba aleasă, pentru o experiență personalizată.",
              en: "Remember your settings, such as the chosen language, for a personalised experience." } },
    { id: "statistics", icon: "statistics",
      name: { ro: "Statistici", en: "Statistics" },
      desc: { ro: "Ne ajută să înțelegem cum este folosit site-ul, prin date agregate și anonime.",
              en: "Help us understand how the site is used, through aggregated and anonymous data." } },
    { id: "marketing", icon: "marketing",
      name: { ro: "Marketing", en: "Marketing" },
      desc: { ro: "Permit afișarea de conținut relevant pe alte platforme și măsurarea campaniilor.",
              en: "Allow relevant content on other platforms and measurement of campaigns." } },
  ];

  return (
    <React.Fragment>
      {/* persistent manage button (after a choice was made) */}
      {stored && !banner && !modal && (
        <button className="ck-fab" aria-label={L({ ro: "Setări cookies", en: "Cookie settings" })}
          onClick={() => window.dispatchEvent(new CustomEvent("fg-open-cookies"))}>
          <CookieIc.cookie />
        </button>
      )}

      {/* first-visit banner */}
      {banner && (
        <div className="ck-banner" role="dialog" aria-live="polite" aria-label="Cookie consent">
          <div className="ck-banner__inner wrap">
            <div className="ck-banner__text">
              <div className="ck-banner__head"><CookieIc.cookie style={{ width: 20 }} />
                <strong>{L({ ro: "Respectăm confidențialitatea ta", en: "We value your privacy" })}</strong>
              </div>
              <p>{L({ ro: "Folosim cookie-uri pentru funcționarea site-ului și, cu acordul tău, pentru statistici, preferințe și marketing. Poți accepta, refuza sau alege ce permiți.",
                     en: "We use cookies to run the site and, with your consent, for statistics, preferences and marketing. You can accept, reject or choose what you allow." })}
                {" "}<a href="#/contact" onClick={() => setBanner(false)}>{L({ ro: "Detalii în Politica de confidențialitate", en: "Details in our Privacy Policy" })}</a>.
              </p>
            </div>
            <div className="ck-banner__actions">
              <button className="btn btn--ghost" onClick={() => setModal(true)}>{L({ ro: "Personalizează", en: "Customise" })}</button>
              <button className="btn btn--ghost" onClick={rejectAll}>{L({ ro: "Refuză toate", en: "Reject all" })}</button>
              <button className="btn btn--primary" onClick={acceptAll}>{L({ ro: "Accept toate", en: "Accept all" })}</button>
            </div>
          </div>
        </div>
      )}

      {/* preferences modal */}
      {modal && (
        <div className="ck-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) setModal(false); }}>
          <div className="ck-modal" role="dialog" aria-modal="true" aria-label={L({ ro: "Preferințe cookies", en: "Cookie preferences" })}>
            <div className="ck-modal__head">
              <h3 className="h-md">{L({ ro: "Preferințe cookies", en: "Cookie preferences" })}</h3>
              <button className="ck-x" onClick={() => setModal(false)} aria-label={L({ ro: "Închide", en: "Close" })}><Ic.close /></button>
            </div>
            <p className="ck-modal__intro muted">{L({ ro: "Alege ce categorii de cookie-uri permiți. Îți poți schimba opțiunile oricând din butonul de setări cookies.",
              en: "Choose which cookie categories you allow. You can change your choices anytime from the cookie-settings button." })}</p>
            <div className="ck-grid">
              {CATS.map(c => {
                const Icon = CookieIc[c.icon];
                const on = c.always ? true : prefs[c.id];
                return (
                  <label key={c.id} className={"ck-cat" + (on ? " is-on" : "") + (c.always ? " is-locked" : "")}>
                    <span className="ck-cat__top">
                      <span className="ck-cat__icon"><Icon style={{ width: 18 }} /></span>
                      <span className="ck-cat__name">{L(c.name)}
                        {c.always && <em>{L({ ro: "(întotdeauna active)", en: "(always active)" })}</em>}
                      </span>
                      <span className={"ck-switch" + (on ? " on" : "")} aria-hidden="true"><span></span></span>
                      <input type="checkbox" checked={on} disabled={c.always}
                        onChange={(e) => setPrefs(p => ({ ...p, [c.id]: e.target.checked }))} />
                    </span>
                    <span className="ck-cat__desc">{L(c.desc)}</span>
                  </label>
                );
              })}
            </div>
            <div className="ck-modal__foot">
              <button className="btn btn--ghost" onClick={rejectAll}>{L({ ro: "Refuză toate", en: "Reject all" })}</button>
              <div className="ck-modal__foot-r">
                <button className="btn btn--ghost" onClick={saveChoices}>{L({ ro: "Salvează preferințele", en: "Save preferences" })}</button>
                <button className="btn btn--primary" onClick={acceptAll}>{L({ ro: "Accept toate", en: "Accept all" })}</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

Object.assign(window, { CookieConsent });
