// ─── App entry ──────────────────────────────────────────────────────────
// Loads content from /content/*.json, then renders the site. Decap CMS
// edits those JSON files via Git → Netlify rebuilds → users see new copy.

const PALETTE_OPTIONS = [
  { id: 'pop',        colors: ['#d5b348', '#1f2347', '#f6efd9', '#f09891'] },
  { id: 'sage',       colors: ['#a8c4a8', '#3a5a3a', '#f5f1e8'] },
  { id: 'terracotta', colors: ['#d4937a', '#8a4a35', '#f6efe6'] },
  { id: 'dusk',       colors: ['#8a96b8', '#3a3f5e', '#ecebf3'] },
  { id: 'ink',        colors: ['#8a8a8a', '#1f1f1f', '#f4f2ec'] },
];

// Inline defaults used only if fetch fails (e.g. opening the HTML file
// directly from disk without a static server). Keeps the page from going
// blank during local development. On Netlify the JSON files are always served.
const FALLBACK = {
  general: window.__FALLBACK_GENERAL__ || {
    names: 'Giuditta e Giacomo',
    nameA: 'Giuditta', nameB: 'Giacomo',
    date: '2026-08-29T16:00:00+02:00',
    dateLabel: 'Sabato · 29 Agosto · 2026',
    dateShort: '29 Agosto 2026',
    heroHand: 'si sposano',
    heroSub: "E vorrebbero averti accanto — un giorno di luce, ulivi e cose vere.",
    heroCta: 'Conferma la tua presenza',
    heroImage: '', heroImageSplit: '',
    scheduleEyebrow: 'Il programma del giorno',
    scheduleTitle: 'Come trascorreremo la giornata',
    scheduleLede: "Una guida orientativa — non preoccuparti di essere puntuale al minuto, l'importante è esserci.",
  },
  schedule: { items: [
    { time: '15:30', title: 'Arrivo degli ospiti', note: 'Calice di benvenuto in giardino' },
    { time: '16:00', title: 'Cerimonia', note: 'Chiesa di Santa Maria' },
    { time: '17:30', title: 'Aperitivo', note: 'Tra gli ulivi' },
    { time: '19:30', title: 'Cena', note: 'Sotto la pergola' },
    { time: '22:30', title: 'Taglio della torta', note: 'Brindisi insieme' },
    { time: '23:00', title: 'Si balla', note: 'Fino a notte fonda' },
  ]},
  gift: {
    eyebrow: 'La nostra lista nozze',
    lede: 'La cosa più importante per noi è la tua presenza.',
    cardHand: 'Viaggio di nozze',
    cardSub: 'Stiamo mettendo da parte per partire, lontano e a lungo.',
    intestatari: 'Giuditta e Giacomo',
    iban: 'IT00 X000 0000 0000 0000 0000 000',
    causale: 'Regalo di nozze — il tuo nome',
    foot: 'In alternativa, scopri le cause che sosteniamo qui sotto.',
  },
  causes: {
    eyebrow: 'Donazioni etiche',
    lede: 'Abbiamo scelto alcune realtà che ci stanno a cuore.',
    items: [],
  },
  photos: {
    eyebrow: 'Le foto della giornata',
    title: 'Condividi i tuoi scatti',
    lede: 'Hai scattato qualcosa di bello? Caricalo qui.',
    successText: 'Grazie — i tuoi scatti sono al sicuro.',
    uploadcarePublicKey: '',
  },
  rsvp: {
    eyebrow: 'RSVP',
    title: 'Ci sarai?',
    lede: 'Faccelo sapere il prima possibile.',
    thanksYes: 'Non vediamo l\'ora di averti con noi.',
    thanksNo: 'Ci dispiace tu non possa esserci, ma capiamo.',
  },
};

async function loadContent() {
  const names = ['general', 'schedule', 'gift', 'causes', 'photos', 'rsvp'];
  const results = await Promise.all(
    names.map(n =>
      fetch(`content/${n}.json`, { cache: 'no-store' })
        .then(r => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
        .catch(err => {
          console.warn(`[content] ${n}.json failed, using fallback:`, err.message);
          return FALLBACK[n];
        })
    )
  );
  return Object.fromEntries(names.map((n, i) => [n, results[i]]));
}

function App() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS);
  const [content, setContent] = React.useState(null);

  React.useEffect(() => { loadContent().then(setContent); }, []);

  React.useEffect(() => {
    document.body.dataset.palette = t.palette;
    document.body.dataset.fontpair = t.fontPair;
  }, [t.palette, t.fontPair]);

  const currentPalette = PALETTE_OPTIONS.find(p => p.id === t.palette) || PALETTE_OPTIONS[0];

  if (!content) {
    return (
      <div className="content-loading">
        <p className="hand">un momento…</p>
      </div>
    );
  }

  return (
    <>
      <Hero tweaks={t} general={content.general} />
      <Schedule general={content.general} schedule={content.schedule} />
      <WeddingGift gift={content.gift} />
      <SocialImpact tweaks={t} causes={content.causes} />
      <Photos photos={content.photos} />
      <Rsvp rsvp={content.rsvp} />
      <Footer general={content.general} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Palette" />
        <TweakColor
          label="Tema cromatico"
          value={currentPalette.colors}
          options={PALETTE_OPTIONS.map(p => p.colors)}
          onChange={(colors) => {
            const match = PALETTE_OPTIONS.find(p => p.colors[0] === colors[0]);
            if (match) setTweak('palette', match.id);
          }}
        />

        <TweakSection label="Tipografia" />
        <TweakSelect
          label="Font pair"
          value={t.fontPair}
          options={[
            { value: 'bricolage_jakarta', label: 'Bricolage + Jakarta (pop)' },
            { value: 'cormorant_jost',  label: 'Cormorant + Jost' },
            { value: 'italiana_inter',  label: 'Italiana + Inter' },
            { value: 'dmserif_manrope', label: 'DM Serif + Manrope' },
          ]}
          onChange={(v) => setTweak('fontPair', v)}
        />

        <TweakSection label="Layout" />
        <TweakSelect
          label="Hero"
          value={t.heroLayout}
          options={[
            { value: 'illustration', label: 'Partecipazione illustrata' },
            { value: 'typographic',  label: 'Tipografico' },
            { value: 'image',        label: 'Foto a tutto schermo' },
            { value: 'split',        label: 'Split: testo + foto' },
          ]}
          onChange={(v) => setTweak('heroLayout', v)}
        />
        <TweakSelect
          label="Donazioni"
          value={t.donationLayout}
          options={[
            { value: 'cards',  label: 'Card a griglia' },
            { value: 'list',   label: 'Lista editoriale' },
            { value: 'mosaic', label: 'Mosaico (1 in evidenza)' },
          ]}
          onChange={(v) => setTweak('donationLayout', v)}
        />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
