// V6 — Copy variants system.
// Each visitor gets a stable seed (localStorage); hero + story copy rotate
// between 4 marketing-aware voices. Re-roll button cycles through.

// Pick a seed 0..3 on first visit, persist it. Exposed setter for re-roll.
const VARIANT_COUNT = 4;

function getVariantSeed() {
  try {
    const stored = localStorage.getItem('hello_variant');
    if (stored !== null) {
      const n = parseInt(stored, 10);
      if (!isNaN(n) && n >= 0 && n < VARIANT_COUNT) return n;
    }
  } catch {}
  const n = Math.floor(Math.random() * VARIANT_COUNT);
  try { localStorage.setItem('hello_variant', String(n)); } catch {}
  return n;
}

function setVariantSeed(n) {
  try { localStorage.setItem('hello_variant', String(n)); } catch {}
}

function rotateVariantSeed() {
  const cur = getVariantSeed();
  const next = (cur + 1) % VARIANT_COUNT;
  setVariantSeed(next);
  return next;
}

// VARIANTS — 4 voices:
// 0 — PROVOCATIVE ("A day. 11 bookings. Zero interruptions.") — short, punchy, kept from V4
// 1 — CONFIDENT ("Il telefono non squilla più.") — declarative, calm authority
// 2 — FOUNDER ("Ho costruito Schedy per smettere di rispondere al telefono.") — personal, first-person
// 3 — EDITORIAL ("Martedì ordinario. L'AI ne fa uno straordinario.") — warm, narrative
const VARIANTS = {
  it: [
    // 0 — Provocative
    {
      hero: {
        kicker: 'MARTEDÌ · 08:00 — 18:00',
        h1: { l1: 'Un giorno.', l2: '11 prenotazioni.', l3: 'Zero interruzioni.' },
        bodyStrong: 'Zero telefonate interrotte.',
        bodyPre: '10 ore. 11 prenotazioni. 3 vocali WhatsApp. 2 cancellazioni gestite.',
      },
      m1H: { pre: 'Sei con ', post: '.' }, m1HAccent: 'Il telefono squilla.',
      m1Body: 'Prima, avresti dovuto scegliere: interrompere il trattamento o perdere la prenotazione. Ora non suona nemmeno — arriva su WhatsApp e Schedy ha già risposto.',
      m2H: 'Un vocale di 47 secondi.', m2HAccent: "L'AI capisce prima che finisca.",
      m2Body: 'Deepgram Nova-3 trascrive in italiano. Keyterm prompting con nomi staff, servizi e clienti frequenti. Riconoscimento automatico dal numero.',
      m3H: 'Reminder automatico.', m3HAccent: 'No-show −60%.',
      m3Body: '24h e 1h prima. Sul canale preferito del cliente. Se risponde, la conferma viene registrata in automatico. Se non risponde, vedi chi probabilmente non si presenterà.',
      m4H: { pre: 'Chiudi con ', post: 'prenotazioni.' }, m4HAccent: 'Non le hai gestite.',
      m4Outro: { l1: 'Domani, stessa storia.', l2: '14 giorni gratis. Setup in 5 minuti. Nessuna carta di credito.' },
      endBody: 'Domani, stessa storia.', endAccent: 'Senza muovere un dito.',
    },
    // 1 — Confident / declarative
    {
      hero: {
        kicker: 'UNA GIORNATA QUALSIASI · DALL\'ALBA AL TRAMONTO',
        h1: { l1: 'Il telefono', l2: 'non squilla più.', l3: 'Il calendario sì.' },
        bodyStrong: "L'assistente AI che risponde al posto tuo.",
        bodyPre: 'Mentre sei con il cliente, Schedy prende le prenotazioni, ascolta i vocali, conferma gli appuntamenti.',
      },
      m1H: { pre: 'Sei con ', post: '.' }, m1HAccent: 'Non senti lo squillo.',
      m1Body: 'Un messaggio su WhatsApp. Un cliente che vuole prenotare. Schedy risponde in <30 secondi, legge il tuo calendario, propone gli slot. Tu non sei interrotto.',
      m2H: 'Un vocale su WhatsApp.', m2HAccent: "L'AI lo trascrive in italiano.",
      m2Body: "Nomi, orari, richieste particolari. Deepgram Nova-3 capisce l'italiano parlato — anche veloce, anche con rumore di fondo. L'intent viene estratto e il calendario aggiornato.",
      m3H: 'Reminder -1h.', m3HAccent: 'No-show dimezzati.',
      m3Body: 'Il messaggio parte automaticamente sul canale preferito del cliente. Conferma, cambio orario, cancellazione: tutto tracciato. Tu vedi solo il risultato.',
      m4H: { pre: 'Hai chiuso con ', post: 'prenotazioni in più.' }, m4HAccent: 'Non hai toccato il telefono.',
      m4Outro: { l1: 'Questo è ogni giorno, non un giorno speciale.', l2: '14 giorni gratis. Setup in 5 minuti. Nessuna carta di credito.' },
      endBody: 'Stessa cosa domani.', endAccent: 'Senza pensarci.',
    },
    // 2 — Founder / first-person
    {
      hero: {
        kicker: 'COSTRUITO IN ITALIA · PER IL MONDO REALE',
        h1: { l1: 'Abbiamo costruito Schedy', l2: 'per smettere di rispondere', l3: 'al telefono.' },
        bodyStrong: 'E ha funzionato.',
        bodyPre: "È un assistente AI vero: parla italiano, legge il calendario, ascolta i vocali WhatsApp. Non è un chatbot.",
      },
      m1H: { pre: 'Con ', post: ' al banco.' }, m1HAccent: 'Il telefono non sa che non puoi rispondere.',
      m1Body: "Ma Schedy sì. Intercetta il messaggio su WhatsApp prima che diventi una telefonata. Risponde con i tuoi orari, il tuo stile, le tue disponibilità.",
      m2H: 'Vocale di 47 secondi. Cliente di fretta.', m2HAccent: "L'AI ha già capito tutto.",
      m2Body: "Abbiamo scelto Deepgram Nova-3 perché trascrive l'italiano meglio di tutti. Nomi, servizi, appuntamenti — estratti in <2 secondi. Il cliente pensa di aver parlato con te.",
      m3H: 'Il reminder parte un\'ora prima.', m3HAccent: 'I no-show crollano.',
      m3Body: 'Abbiamo visto saloni dimezzare le assenze dalla settimana 1. Il segreto non è solo ricordare — è farlo sul canale giusto, con il tono giusto, al momento giusto.',
      m4H: { pre: 'Stasera: ', post: 'prenotazioni in più,' }, m4HAccent: 'zero fatica.',
      m4Outro: { l1: "Domani inizi la giornata con l'agenda piena.", l2: '14 giorni gratis. Setup in 5 minuti. Nessuna carta di credito.' },
      endBody: 'Questa è la nuova normalità.', endAccent: 'Benvenuto nel 2026.',
    },
    // 3 — Editorial / narrative
    {
      hero: {
        kicker: 'UN MARTEDÌ COME TANTI · O FORSE NO',
        h1: { l1: 'Martedì ordinario.', l2: "L'AI ne fa", l3: 'uno straordinario.' },
        bodyStrong: 'Tutto in automatico.',
        bodyPre: 'Mentre fai il tuo mestiere, qualcuno prende appunti, risponde ai messaggi, aggiorna il calendario.',
      },
      m1H: { pre: 'Entra ', post: '. Il telefono vibra.' }, m1HAccent: 'Tu, per una volta, resti.',
      m1Body: 'Schedy ha già letto il messaggio, aperto il calendario, proposto tre slot. Mentre stringi la mano al cliente, una prenotazione si scrive da sola sull\'agenda di domani.',
      m2H: 'Un vocale. Lingua veloce, dialetto, rumore.', m2HAccent: 'Schedy non si perde un nome.',
      m2Body: 'Deepgram Nova-3 lavora in italiano come nessun altro. Trascrizione, comprensione, prenotazione — in un minuto scarso dalla ricezione. Il cliente riceve conferma prima di riprendere l\'auto.',
      m3H: "C'è un'ora alla prossima seduta.", m3HAccent: 'Il reminder parte da solo.',
      m3Body: "Il cliente conferma con un'emoji. Schedy lo registra, aggiorna lo stato, avvisa lo staff. Se non risponde, l'agenda si prepara al possibile slot libero. Niente drama.",
      m4H: { pre: '18:00. ', post: 'appuntamenti in più.' }, m4HAccent: 'Tu nemmeno sai come.',
      m4Outro: { l1: "E domani si ricomincia, senza che tu debba ricominciare.", l2: '14 giorni gratis. Setup in 5 minuti. Nessuna carta di credito.' },
      endBody: 'Domani un altro martedì.', endAccent: 'Identico — e diverso.',
    },
  ],
  en: [
    // 0 — Provocative
    {
      hero: {
        kicker: 'TUESDAY · 08:00 — 18:00',
        h1: { l1: 'One day.', l2: '11 bookings.', l3: 'Zero interruptions.' },
        bodyStrong: 'Zero interrupted calls.',
        bodyPre: '10 hours. 11 bookings. 3 WhatsApp voice notes. 2 cancellations handled.',
      },
      m1H: { pre: "You're with ", post: '.' }, m1HAccent: 'The phone rings.',
      m1Body: "Before, you had to choose: interrupt the treatment or lose the booking. Now it doesn't even ring — it comes in on WhatsApp and Schedy already replied.",
      m2H: 'A 47-second voice note.', m2HAccent: 'AI gets it before it ends.',
      m2Body: 'Deepgram Nova-3 transcribes Italian. Keyterm prompting with staff names, services and frequent clients. Auto-recognition from phone number.',
      m3H: 'Automatic reminder.', m3HAccent: 'No-shows −60%.',
      m3Body: "24h and 1h before. On the client's preferred channel. If they reply, confirmation is logged automatically. If they don't, you see who likely won't show up.",
      m4H: { pre: 'You close with ', post: 'bookings.' }, m4HAccent: "You didn't handle them.",
      m4Outro: { l1: 'Tomorrow, same story.', l2: '14 days free. 5-minute setup. No credit card.' },
      endBody: 'Tomorrow, same story.', endAccent: "Without lifting a finger.",
    },
    // 1 — Confident
    {
      hero: {
        kicker: 'AN ORDINARY DAY · FROM DAWN TO DUSK',
        h1: { l1: "The phone", l2: "doesn't ring anymore.", l3: 'The calendar does.' },
        bodyStrong: 'The AI assistant that answers for you.',
        bodyPre: "While you're with the client, Schedy takes bookings, listens to voice notes, confirms appointments.",
      },
      m1H: { pre: "You're with ", post: '.' }, m1HAccent: "You don't hear the ring.",
      m1Body: "A WhatsApp message. A client wants to book. Schedy replies in <30s, reads your calendar, proposes slots. You are not interrupted.",
      m2H: 'A WhatsApp voice note.', m2HAccent: 'The AI transcribes it in Italian.',
      m2Body: 'Names, times, special requests. Deepgram Nova-3 understands spoken Italian — fast, noisy, dialectal. Intent is parsed, calendar updated.',
      m3H: 'Reminder -1h.', m3HAccent: 'No-shows cut in half.',
      m3Body: "The message goes out automatically on the client's preferred channel. Confirm, reschedule, cancel — all tracked. You only see the result.",
      m4H: { pre: 'You closed with ', post: 'extra bookings.' }, m4HAccent: "You didn't touch the phone.",
      m4Outro: { l1: 'This is every day, not a special one.', l2: '14 days free. 5-minute setup. No credit card.' },
      endBody: 'Same thing tomorrow.', endAccent: 'Without thinking about it.',
    },
    // 2 — Founder
    {
      hero: {
        kicker: 'BUILT IN ITALY · FOR THE REAL WORLD',
        h1: { l1: 'We built Schedy', l2: 'to stop answering', l3: 'the phone.' },
        bodyStrong: 'And it worked.',
        bodyPre: "It's a real AI assistant: speaks Italian, reads the calendar, listens to WhatsApp voice notes. Not a chatbot.",
      },
      m1H: { pre: 'With ', post: ' at the counter.' }, m1HAccent: "The phone doesn't know you can't answer.",
      m1Body: "But Schedy does. It catches the WhatsApp message before it becomes a call. Replies with your hours, your style, your availability.",
      m2H: "47-second voice note. Client in a rush.", m2HAccent: "The AI already got it all.",
      m2Body: "We picked Deepgram Nova-3 because it transcribes Italian best. Names, services, appointments — extracted in <2s. The client thinks they talked to you.",
      m3H: 'The reminder fires an hour before.', m3HAccent: 'No-shows collapse.',
      m3Body: "We've seen salons halve no-shows from week 1. The trick isn't just reminding — it's the right channel, the right tone, the right moment.",
      m4H: { pre: 'Tonight: ', post: 'extra bookings,' }, m4HAccent: 'zero effort.',
      m4Outro: { l1: "Tomorrow you start with a full calendar.", l2: '14 days free. 5-minute setup. No credit card.' },
      endBody: 'This is the new normal.', endAccent: 'Welcome to 2026.',
    },
    // 3 — Editorial
    {
      hero: {
        kicker: 'AN ORDINARY TUESDAY · OR MAYBE NOT',
        h1: { l1: 'Ordinary Tuesday.', l2: 'AI makes it', l3: 'extraordinary.' },
        bodyStrong: 'All on autopilot.',
        bodyPre: "While you do your craft, someone takes notes, answers messages, updates the calendar.",
      },
      m1H: { pre: 'In walks ', post: '. Phone buzzes.' }, m1HAccent: 'You, for once, stay.',
      m1Body: "Schedy already read the message, opened the calendar, proposed three slots. As you shake the client's hand, a booking writes itself into tomorrow's schedule.",
      m2H: 'A voice note. Fast, dialectal, noisy.', m2HAccent: "Schedy doesn't miss a name.",
      m2Body: "Deepgram Nova-3 works in Italian like nothing else. Transcription, understanding, booking — under a minute from receipt. The client gets confirmation before driving off.",
      m3H: "One hour till the next session.", m3HAccent: 'Reminder fires on its own.',
      m3Body: "The client confirms with an emoji. Schedy logs it, updates the status, notifies staff. If they don't answer, the schedule braces for a free slot. No drama.",
      m4H: { pre: '18:00. ', post: 'extra appointments.' }, m4HAccent: 'You barely know how.',
      m4Outro: { l1: "Tomorrow it all starts again — without you starting anything.", l2: '14 days free. 5-minute setup. No credit card.' },
      endBody: 'Another Tuesday tomorrow.', endAccent: 'Identical — and different.',
    },
  ],
};

function getVariant(lang, seed) {
  const n = seed ?? getVariantSeed();
  return VARIANTS[lang]?.[n] || VARIANTS.it[0];
}

// Replace hardcoded source weekday ("martedì" IT / "Tuesday" EN) with the
// visitor's actual current weekday. Same pattern as hello-site-v4. Runs once
// at module load — VARIANTS is mutated in place. VERTICALS data stays
// untouched so in-dialog transcripts keep their literal references.
(function injectTodayIntoVariants() {
  function dayName(lang, casing) {
    const locale = lang === 'en' ? 'en-US' : 'it-IT';
    const lower = new Intl.DateTimeFormat(locale, { weekday: 'long' }).format(new Date()).toLowerCase();
    if (casing === 'upper') return lower.toUpperCase();
    if (casing === 'capital') return lower.charAt(0).toUpperCase() + lower.slice(1);
    return lower;
  }
  function localize(node, lang) {
    if (typeof node === 'string') {
      const lo = dayName(lang, 'lower');
      const ca = dayName(lang, 'capital');
      const up = dayName(lang, 'upper');
      if (lang === 'it') {
        return node.replace(/MARTEDÌ/g, up).replace(/Martedì/g, ca).replace(/martedì/g, lo);
      }
      return node.replace(/TUESDAY/g, up).replace(/Tuesday/g, ca).replace(/tuesday/g, lo);
    }
    if (Array.isArray(node)) return node.map(n => localize(n, lang));
    if (node && typeof node === 'object') {
      const out = {};
      for (const k in node) out[k] = localize(node[k], lang);
      return out;
    }
    return node;
  }
  VARIANTS.it = localize(VARIANTS.it, 'it');
  VARIANTS.en = localize(VARIANTS.en, 'en');
})();

Object.assign(window, { VARIANTS, VARIANT_COUNT, getVariantSeed, setVariantSeed, rotateVariantSeed, getVariant });
