// tokens2.jsx — v2 design tokens (theme is DYNAMIC: applyTheme mutates window.T
// from tweak state before each render). Same window exports as v1 so the
// feedback flow and admin dashboard render against the new system unchanged.

const T = {
  color: {}, grad: {}, font: {},
  radius: { card: 14, input: 10, btn: 999, pill: 999, chip: 10 },
  shadow: {},
  maxForm: 520,
  maxDash: 760,
};

// hex → rgba helper
function rgba(hex, a) {
  const n = parseInt(hex.slice(1), 16);
  return 'rgba(' + (n >> 16) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + a + ')';
}

const ACCENTS = {
  '#A87C2A': { deep: '#7E5C1D', name: 'Gold' },
  '#B45309': { deep: '#8A3E0A', name: 'Amber' },
  '#4F6E5D': { deep: '#3B5446', name: 'Sage' },
};

const DIRECTIONS = {
  gallery: {
    bg: '#FAF8F3', surface: '#FFFFFF', line: '#E8E1D4',
    ink: '#221B12', sub: '#6E6153', faint: '#A29685',
    field: '#FFFEFB', wash: 0.10,
  },
  atelier: {
    bg: '#F6EEDF', surface: '#FFFDF7', line: '#E1D3B8',
    ink: '#2A1F12', sub: '#71604A', faint: '#9C8C74',
    field: '#FFFCF4', wash: 0.26,
  },
};

// Mutates window.T from tweak state. Call at the top of App's render.
function applyTheme(t) {
  const D = DIRECTIONS[t.direction] || DIRECTIONS.gallery;
  const acc = ACCENTS[t.accent] ? t.accent : '#A87C2A';
  const deep = ACCENTS[acc].deep;

  T.color = {
    bg: D.bg, card: D.surface, border: D.line, field: D.field,
    text: D.ink, textSoft: D.sub, textFaint: D.faint,
    amber: acc, amberLight: rgba(acc, 0.10), amberDeep: deep,
    sage: '#6B8E7B', sageLight: '#EAEFE7', sageDeep: '#4F6E5D',
    link: deep, danger: '#B0402A',
    parchment: D.bg, espresso: D.ink,
    gold: acc, accent: acc, accentDeep: deep, accentSoft: rgba(acc, 0.10),
    wash: D.wash,
  };
  T.grad = {
    brand: acc, // solid — progress fill etc.
    divider: 'linear-gradient(90deg, transparent, ' + rgba(acc, 0.6) + ', transparent)',
  };
  T.font = {
    display: t.serif || "'Cormorant Garamond', Georgia, serif",
    head: "'Nunito Sans', system-ui, sans-serif",
    body: "'Nunito Sans', system-ui, sans-serif",
  };
  T.shadow = {
    soft: '0 2px 10px rgba(34,27,18,0.05)',
    card: '0 8px 28px rgba(34,27,18,0.07)',
    lift: '0 18px 40px rgba(34,27,18,0.14)',
    glow: '0 4px 14px ' + rgba(acc, 0.28),
  };

  // expose to CSS (focus rings, hover states, default links)
  const r = document.documentElement.style;
  r.setProperty('--acc', acc);
  r.setProperty('--acc-deep', deep);
  r.setProperty('--acc-soft', rgba(acc, 0.14));
  r.setProperty('--ink', D.ink);
  r.setProperty('--line', D.line);
  r.setProperty('--bg', D.bg);
  return T;
}

// ── Module registry ──────────────────────────────────────────
const MODULES = [
  { id: 'feedback',  label: 'Reader Feedback', short: 'Feedback', icon: '✦', status: 'live', blurb: 'Share your thoughts on the test copy.' },
  { id: 'marketing', label: 'About the Series', short: 'About',    icon: '✦', status: 'soon', blurb: 'The mission, the books, and the story behind Book of Light.' },
  { id: 'store',     label: 'Store',            short: 'Store',    icon: '✦', status: 'soon', blurb: 'Print, ebook and bundle editions — Universal & Islamic, in multiple languages.' },
  { id: 'ebook',     label: 'Ebook Reader',     short: 'Read',     icon: '✦', status: 'soon', blurb: 'Read your purchased books right in the browser.' },
  { id: 'audiobook', label: 'Audiobook',        short: 'Listen',   icon: '✦', status: 'soon', blurb: 'Narrated stories for bedtime and the car.' },
  { id: 'games',     label: 'Games',            short: 'Games',    icon: '✦', status: 'soon', blurb: 'Story quizzes, puzzles and colouring — play inside the world of the books.' },
  { id: 'generator', label: 'Custom Ebook',     short: 'Custom',   icon: '✦', status: 'soon', blurb: 'Assemble a personalised edition by theme and language.' },
  { id: 'members',   label: 'Members Area',     short: 'Members',  icon: '✦', status: 'soon', blurb: 'Animation previews and early access for the inner circle.' },
  { id: 'beta',      label: 'Beta Reader',      short: 'Apply',    icon: '✦', status: 'soon', blurb: 'Apply to receive a test copy and a reader code.' },
];

// ── Storage adapter (identical contract to v1) ───────────────
const storage = {
  async get(key) {
    try {
      if (window.storage && typeof window.storage.get === 'function') {
        const v = await window.storage.get(key);
        if (v !== null && v !== undefined) return v;
      }
    } catch (e) { /* fall through */ }
    try {
      const raw = localStorage.getItem(key);
      return raw ? JSON.parse(raw) : null;
    } catch (e) { return null; }
  },
  async set(key, value) {
    try {
      if (window.storage && typeof window.storage.set === 'function') {
        await window.storage.set(key, value);
      }
    } catch (e) { /* ignore */ }
    try { localStorage.setItem(key, JSON.stringify(value)); } catch (e) { /* ignore */ }
  },
};
const KEYS = { feedback: 'feedback:entries' };

// ── Helpers ──────────────────────────────────────────────────
const uid = () => Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7);

const fmtDate = (iso) => {
  try {
    const d = new Date(iso);
    return d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) +
      ', ' + d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
  } catch (e) { return iso; }
};

const ROLES = ['Parent', 'Teacher', 'Librarian', 'Child (with parent)', 'Faith Leader', 'Other'];

const PROMPTS = [
  { key: 'resonated',    label: 'Which story resonated most with your child or family?', max: 500 },
  { key: 'conversation', label: 'How did the book spark conversation about faith or unity?', max: 500 },
  { key: 'improve',      label: 'What would you change or improve?', max: 500 },
  { key: 'favourite',    label: 'Any favourite illustrations or moments?', max: 500 },
];

// No admin credential lives in client source. The dashboard authenticates
// against /api/admin/entries using a token held in sessionStorage.
const TEST_ACCESS_CODE = 'TEST-2026';
const BOOK_TITLE = 'The Book of Light';
const TAGLINE = 'Stories that celebrate what unites us.';

Object.assign(window, { T, applyTheme, rgba, MODULES, storage, KEYS, uid, fmtDate, ROLES, PROMPTS, TEST_ACCESS_CODE, BOOK_TITLE, TAGLINE });
