/* Tweaks — display-font selector + per-page color-scheme picker.
   Persisted via the host's __edit_mode_set_keys protocol.

   Color schemes recolor the dominant color block on each page:
   • interior pages → the PageHeader masthead (--ph-bg / --ph-fg / --ph-accent)
   • home           → the full-bleed Banner band
   Each page stores its own choice under a distinct key (scheme_<page>), so a
   scheme picked on "Explore" doesn't bleed onto "The Weekend". */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "displayFont": "LesEnfantsDuParadis",
  "scheme_home": ["#a4970d", "#F0E8D0", "#e0da3a"],
  "scheme_weekend": ["#6D1727", "#F0E8D0", "#CBC62F"],
  "scheme_travel": ["#76151E", "#F0E8D0", "#e0da3a"],
  "scheme_explore": ["#263342", "#F0E8D0", "#B7D9FF"],
  "scheme_faq": ["#410016", "#F0E8D0", "#d50e12"],
  "scheme_registry": ["#a4970d", "#F0E8D0", "#e0da3a"]
}/*EDITMODE-END*/;

const DISPLAY_FONTS = [
  { id: 'OnlyYou',             label: 'Only You',              stack: "'OnlyYou', 'Bristol', Georgia, serif" },
  { id: 'Bristol',             label: 'Bristol',               stack: "'Bristol', Georgia, serif" },
  { id: 'LesEnfantsDuParadis', label: 'Les Enfants du Paradis',stack: "'LesEnfantsDuParadis', 'Bristol', Georgia, serif" },
  { id: 'RandomHandwritten',   label: 'Random Handwritten',    stack: "'RandomHandwritten', 'Bristol', Georgia, serif" },
  { id: 'SimpleNotes',         label: 'Simple Notes',          stack: "'SimpleNotes', 'Bristol', Georgia, serif" },
  { id: 'AHundredMiles',       label: 'A Hundred Miles',       stack: "'AHundredMiles', 'Bristol', Georgia, serif" },
  { id: 'Desyrel',             label: 'Desyrel',               stack: "'Desyrel', 'Bristol', Georgia, serif" },
  { id: 'LaBelleAurore',       label: 'La Belle Aurore',       stack: "'LaBelleAurore', 'Bristol', Georgia, serif" },
];

/* Curated color schemes — every palette is [background, foreground, accent],
   all sourced one-to-one from the brand variables in styles.css. */
const SCHEMES = [
  { id: 'pine',      label: 'Pine & Gold',      colors: ['#2d4535', '#F0E8D0', '#e0da3a'] },
  { id: 'bordeaux',  label: 'Bordeaux & Red',   colors: ['#410016', '#F0E8D0', '#d50e12'] },
  { id: 'olive',     label: 'Olive & Gold',     colors: ['#a4970d', '#F0E8D0', '#e0da3a'] },
  { id: 'wine',      label: 'Wine & Citron',    colors: ['#6D1727', '#F0E8D0', '#CBC62F'] },
  { id: 'oxblood',   label: 'Oxblood & Gold',   colors: ['#76151E', '#F0E8D0', '#e0da3a'] },
  { id: 'slate',     label: 'Slate & Sky',      colors: ['#263342', '#F0E8D0', '#B7D9FF'] },
  { id: 'crimson',   label: 'Crimson & Copper', colors: ['#691e3f', '#F0E8D0', '#CFA182'] },
  { id: 'parchment', label: 'Parchment & Wine', colors: ['#F0E8D0', '#410016', '#d50e12'] },
];

/* Which page are we on? Derived from the file name so it's stable across
   the multi-page site. */
const PAGE = (() => {
  const f = decodeURIComponent((location.pathname.split('/').pop() || '')).toLowerCase();
  if (f.includes('explore'))  return 'explore';
  if (f.includes('weekend'))  return 'weekend';
  if (f.includes('travel'))   return 'travel';
  if (f.includes('faq'))      return 'faq';
  if (f.includes('registry')) return 'registry';
  if (f.includes('rsvp'))     return 'rsvp';
  return 'home';
})();

const PAGE_LABEL = {
  home: 'Home', weekend: 'The Weekend', travel: 'Travel & Stay',
  explore: 'Explore', faq: 'FAQ', registry: 'Registry', rsvp: 'RSVP',
};

function TweaksApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const schemeKey = 'scheme_' + PAGE;
  const scheme = t[schemeKey];
  const hasScheme = Array.isArray(scheme); // rsvp has no recolorable band

  // Apply font change to the document immediately.
  React.useEffect(() => {
    const f = DISPLAY_FONTS.find(x => x.id === t.displayFont)
      || DISPLAY_FONTS.find(x => x.id === 'LesEnfantsDuParadis')
      || DISPLAY_FONTS[0];
    document.documentElement.style.setProperty('--font-display', f.stack);
  }, [t.displayFont]);

  // Apply the current page's color scheme to its dominant color block.
  React.useEffect(() => {
    if (!hasScheme) return;
    const [bg, fg, accent] = scheme;

    const masthead = document.querySelector('[data-page-masthead]');
    if (masthead) {
      masthead.style.setProperty('--ph-bg', bg);
      masthead.style.setProperty('--ph-fg', fg);
      masthead.style.setProperty('--ph-accent', accent);
    }

    // Home page: recolor the full-bleed Banner band (bg + text + dots).
    const banner = document.querySelector('.banner');
    if (banner) {
      banner.style.background = bg;
      banner.style.color = accent;
      banner.querySelectorAll('.dot').forEach(d => { d.style.color = accent; });
    }
  }, [hasScheme, scheme && scheme[0], scheme && scheme[1], scheme && scheme[2]]);

  const activeScheme = hasScheme
    ? SCHEMES.find(s => JSON.stringify(s.colors).toLowerCase() === JSON.stringify(scheme).toLowerCase())
    : null;

  return (
    <TweaksPanel title="Tweaks">
      {hasScheme && (
        <TweakSection label={`Color scheme · ${PAGE_LABEL[PAGE]}`}>
          <TweakColor
            label="Palette"
            value={scheme}
            options={SCHEMES.map(s => s.colors)}
            onChange={(v) => setTweak(schemeKey, v)} />
          <div style={{
            fontSize: 11,
            color: 'rgba(41,38,27,.55)',
            fontStyle: activeScheme ? 'normal' : 'italic',
            marginTop: -2,
          }}>
            {activeScheme ? activeScheme.label : 'Custom palette'}
          </div>
        </TweakSection>
      )}

      <TweakSection label="Display font">
        <div style={{ display: 'grid', gap: 8 }}>
          {DISPLAY_FONTS.map(f => {
            const active = t.displayFont === f.id;
            return (
              <button
                key={f.id}
                type="button"
                onClick={() => setTweak('displayFont', f.id)}
                style={{
                  display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
                  gap: 12,
                  padding: '12px 14px',
                  background: active ? 'rgba(213, 14, 18, 0.08)' : 'transparent',
                  color: active ? 'var(--flag-red, #d50e12)' : 'inherit',
                  border: `1px solid ${active ? 'var(--flag-red, #d50e12)' : 'rgba(120, 113, 15, 0.35)'}`,
                  borderRadius: 0,
                  cursor: 'pointer',
                  fontFamily: 'inherit',
                  textAlign: 'left',
                  transition: 'all 180ms ease',
                }}
              >
                <span style={{
                  fontFamily: f.stack,
                  fontSize: 28,
                  lineHeight: 1,
                  color: active ? 'var(--flag-red, #d50e12)' : 'var(--ink, #1E1C0A)',
                }}>
                  Sydney &amp; Andrés
                </span>
                <span style={{
                  fontSize: 11,
                  letterSpacing: '0.18em',
                  textTransform: 'uppercase',
                  opacity: 0.75,
                  whiteSpace: 'nowrap',
                }}>{f.label}</span>
              </button>
            );
          })}
        </div>
      </TweakSection>
    </TweaksPanel>
  );
}

window.TweaksApp = TweaksApp;
