// Cookies & Privacy — settings screen + first-visit consent banner.

const COOKIE_CONSENT_KEY = "catalogue_maker_cookie_consent";  // stored as JSON: { necessary, functional, analytics, marketing, decidedAt }

const DEFAULT_CONSENT = { necessary: true, functional: true, analytics: false, marketing: false };

const CATEGORIES = [
  { id: "necessary",  title: "Strictly necessary",
    desc: "Required for the app to function: authentication, security, load balancing. Cannot be disabled.",
    examples: ["session_id", "csrf_token", "catalogue_maker_auth"],
    locked: true,
  },
  { id: "functional", title: "Functional",
    desc: "Remember your preferences such as theme, language, and sidebar state.",
    examples: ["theme_pref", "sidebar_state", "last_project"],
  },
  { id: "analytics",  title: "Analytics",
    desc: "Help us understand how the app is used so we can improve it. Aggregated and anonymized.",
    examples: ["_ga", "page_views", "session_duration"],
  },
  { id: "marketing",  title: "Marketing",
    desc: "Used to show relevant product news and offers. Disabled by default for internal accounts.",
    examples: ["campaign_id", "referrer"],
  },
];

// =================================================================
// Consent banner — shown until the user makes a choice
// =================================================================
const CookieBanner = () => {
  const [consent, setConsent] = React.useState(() => cookies.getJSON(COOKIE_CONSENT_KEY));
  const [showCustom, setShowCustom] = React.useState(false);
  const [draft, setDraft] = React.useState(DEFAULT_CONSENT);

  const persist = (c) => {
    const value = { ...c, decidedAt: new Date().toISOString() };
    cookies.set(COOKIE_CONSENT_KEY, value, { days: 365 });
    setConsent(value);
    window.dispatchEvent(new CustomEvent("hx-cookie-consent", { detail: value }));
    window.__toast && window.__toast("Cookie preferences saved");
  };

  if (consent) return null;

  return (
    <div className="hx-cookie-banner" role="dialog" aria-label="Cookie preferences">
      <div className="hx-cb-inner">
        {!showCustom ? (
          <>
            <div className="hx-cb-text">
              <strong>We use cookies</strong> to keep you signed in, remember your preferences, and improve the product. You can adjust which types you allow.
              {" "}<a className="hx-link" href="#/cookies" onClick={(e) => { e.preventDefault(); window.__nav && window.__nav("cookies"); }}>Learn more</a>.
            </div>
            <div className="hx-cb-actions">
              <Btn kind="ghost" onClick={() => setShowCustom(true)}>Customize</Btn>
              <Btn kind="secondary" onClick={() => persist({ ...DEFAULT_CONSENT, analytics: false, marketing: false })}>Necessary only</Btn>
              <Btn kind="primary"   onClick={() => persist({ necessary: true, functional: true, analytics: true, marketing: true })}>Accept all</Btn>
            </div>
          </>
        ) : (
          <>
            <div className="hx-cb-customize">
              <div style={{ fontWeight: 600, marginBottom: 4 }}>Customize cookies</div>
              <div style={{ color: "var(--muted)", fontSize: 13, marginBottom: 12 }}>Pick which categories you allow. You can change this anytime.</div>
              <div className="hx-cb-cats">
                {CATEGORIES.map(c => (
                  <label key={c.id} className="hx-cb-cat">
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 13.5 }}>{c.title}</div>
                      <div style={{ color: "var(--muted)", fontSize: 12, marginTop: 2 }}>{c.desc}</div>
                    </div>
                    <Toggle
                      checked={c.locked ? true : draft[c.id]}
                      onChange={(v) => !c.locked && setDraft({ ...draft, [c.id]: v })}
                    />
                  </label>
                ))}
              </div>
            </div>
            <div className="hx-cb-actions">
              <Btn kind="secondary" onClick={() => setShowCustom(false)}>Back</Btn>
              <Btn kind="primary"   onClick={() => persist(draft)}>Save preferences</Btn>
            </div>
          </>
        )}
      </div>
      <style>{`
        .hx-cookie-banner {
          position: fixed; bottom: 16px; left: 16px; right: 16px; max-width: 720px;
          margin: 0 auto;
          background: var(--panel); border: 1px solid var(--line);
          border-radius: 14px; box-shadow: var(--shadow-modal);
          z-index: 75;
          animation: hxslideup .25s cubic-bezier(.2,.9,.3,1.05) both;
        }
        @keyframes hxslideup { from { transform: translateY(20px); opacity: 0; } to { transform: none; opacity: 1; } }
        .hx-cb-inner { padding: 16px 18px; display: flex; flex-direction: column; gap: 12px; }
        .hx-cb-text { font-size: 13.5px; line-height: 1.55; }
        .hx-cb-actions { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
        .hx-cb-cats { display: flex; flex-direction: column; gap: 6px; }
        .hx-cb-cat { display: flex; gap: 14px; align-items: flex-start; justify-content: space-between; padding: 10px; border-radius: 8px; border: 1px solid var(--line-2); }
        @media (max-width: 640px) {
          .hx-cookie-banner { left: 10px; right: 10px; bottom: 10px; }
          .hx-cb-actions > button { flex: 1; justify-content: center; }
        }
      `}</style>
    </div>
  );
};

// =================================================================
// Settings page — manage consent + view all cookies in use
// =================================================================
const CookiesScreen = () => {
  const [consent, setConsent] = React.useState(() => cookies.getJSON(COOKIE_CONSENT_KEY) || DEFAULT_CONSENT);
  const [active, setActive] = React.useState(cookies.all());
  const refreshActive = () => setActive(cookies.all());

  const update = (id, value) => {
    const next = { ...consent, [id]: value, decidedAt: new Date().toISOString() };
    cookies.set(COOKIE_CONSENT_KEY, next, { days: 365 });
    setConsent(next);
    window.__toast(`${CATEGORIES.find(c => c.id === id)?.title} cookies ${value ? "enabled" : "disabled"}`);
  };

  const clearAll = () => {
    const c = cookies.all();
    Object.keys(c).forEach(name => {
      if (name !== COOKIE_CONSENT_KEY) cookies.remove(name);
    });
    refreshActive();
    window.__toast("Non-essential cookies cleared");
  };

  const consentDate = consent.decidedAt ? fmt.dateTime(consent.decidedAt) : null;

  return (
    <div className="hx-screen">
      <ScreenHeader icon={<IconShield size={20}/>} title="Cookies & Privacy"
        subtitle="Control which cookies this app stores and review what's currently active." />

      <Card title="Your preferences" subtitle={consentDate ? `Last updated ${consentDate}.` : "You haven't set preferences yet."}>
        <div className="hx-cookie-cats">
          {CATEGORIES.map(c => (
            <div key={c.id} className="hx-cookie-cat">
              <div className="hx-cookie-cat-main">
                <div>
                  <div className="hx-cookie-cat-title">
                    {c.title}
                    {c.locked && <Pill tone="neutral">Always on</Pill>}
                  </div>
                  <div className="hx-cookie-cat-desc">{c.desc}</div>
                </div>
                <Toggle
                  checked={c.locked ? true : !!consent[c.id]}
                  onChange={(v) => !c.locked && update(c.id, v)}
                />
              </div>
              {c.examples?.length > 0 && (
                <details className="hx-cookie-examples">
                  <summary>Examples ({c.examples.length})</summary>
                  <div className="hx-cookie-tags">
                    {c.examples.map(e => <code key={e} className="hx-cookie-tag">{e}</code>)}
                  </div>
                </details>
              )}
            </div>
          ))}
        </div>
      </Card>

      <Card title="Active cookies" subtitle={`${Object.keys(active).length} stored in your browser for this site.`}
        action={<Btn kind="secondary" size="sm" onClick={refreshActive}>Refresh</Btn>}>
        {Object.keys(active).length === 0 ? (
          <EmptyState icon={<IconShield size={36}/>} title="No cookies stored"
            description="This site hasn't stored any cookies in your browser yet."/>
        ) : (
          <Table
            columns={[
              { key: "name",  label: "Name", render: (r) => <span style={{ fontFamily: "var(--mono)", fontSize: 12.5 }}>{r.name}</span> },
              { key: "value", label: "Value", render: (r) => <span style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--muted)" }}>{fmt.truncate(r.value, 36)}</span> },
              { key: "action", label: "", w: 60, align: "right",
                render: (r) => <Tooltip content="Remove cookie">
                  <button className="hx-icon-btn" onClick={() => { cookies.remove(r.name); refreshActive(); window.__toast(`Removed "${r.name}"`); }}>
                    <IconTrash size={14}/>
                  </button>
                </Tooltip>
              },
            ]}
            rows={Object.entries(active).map(([name, value]) => ({ id: name, name, value }))}
          />
        )}
      </Card>

      <DangerZone
        title="Clear all non-essential cookies"
        description="Removes functional, analytics, and marketing cookies. You'll keep your sign-in session."
        actionLabel="Clear cookies"
        onConfirm={clearAll}
      />

      <style>{`
        .hx-cookie-cats { display: flex; flex-direction: column; gap: 12px; }
        .hx-cookie-cat { padding: 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel-2); }
        .hx-cookie-cat-main { display: flex; justify-content: space-between; align-items: flex-start; gap: 14px; }
        .hx-cookie-cat-title { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 14px; }
        .hx-cookie-cat-desc { color: var(--muted); font-size: 13px; margin-top: 4px; line-height: 1.5; max-width: 560px; }
        .hx-cookie-examples { margin-top: 10px; }
        .hx-cookie-examples summary { font-size: 12.5px; color: var(--muted); cursor: pointer; user-select: none; }
        .hx-cookie-examples summary:hover { color: var(--ink-2); }
        .hx-cookie-tags { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
        .hx-cookie-tag { background: var(--panel); border: 1px solid var(--line); border-radius: 4px; padding: 2px 7px; font-family: var(--mono); font-size: 11.5px; color: var(--ink-2); }
      `}</style>
    </div>
  );
};

Object.assign(window, { CookieBanner, CookiesScreen, DEFAULT_CONSENT });
