/* global React */
const { useState: useS } = React;

/* Copy supplements for Team / FAQ / Booking — merged into COPY[lang] by main app */
window.EXTRA_COPY = {
  de: {
    nav: ["Leistungen", "Referenzen", "Über uns", "FAQ", "Termin", "Kontakt"],
    teamEyebrow: "Team",
    teamEyebrow: "Wer",
    teamTitle: "Ein Mann,\nein Anschluss.",
    teamSub: "Markus Unterkofler — ausgebildet, Meister, vor Ort. Kein Callcenter, kein Subunternehmer.",
    team: [
      { name: "Markus Unterkofler", role: "Inhaber & Meister", since: "seit 2019", phone: "+39 347 948 9636" },
    ],
    faqEyebrow: "FAQ",
    faqTitle: "Häufige Fragen.",
    faqs: [
      { q: "Wie schnell kommt ihr nach einem Anruf?", a: "Werktags melde ich mich innerhalb von 48 Stunden zurück. Bei echten Notfällen (Stromausfall, Wasserschaden mit Strom) versuche ich noch am selben Tag vorbeizukommen — ruf direkt durch." },
      { q: "Macht ihr auch nur kleine Sachen?", a: "Ja — Schalter tauschen, Lampe montieren, Dose nachsetzen. Kleinaufträge unter zwei Stunden rechne ich pauschal ab, ohne Anfahrt-Aufschlag im Etschtal." },
      { q: "Wie läuft Photovoltaik konkret ab?", a: "1) Termin vor Ort + Dachvermessung. 2) Angebot mit Ertragsschätzung. 3) Anmeldung bei E-Werk + GSE. 4) Montage in 1–2 Tagen. 5) Inbetriebnahme + Monitoring-App eingerichtet. Du musst nichts selbst beim Amt machen." },
      { q: "Welche Hersteller verbaut ihr?", a: "Bei PV vor allem SunPower, Meyer Burger und Fronius-Wechselrichter. Bei Elektro Gewiss/Vimar/Bticino. Glasfaser von Telmekom-Standard. Kein Lock-in — wenn du was Bestimmtes willst, sag's einfach." },
      { q: "Was kostet ein Lokalaugenschein?", a: "Bei Privatkunden im Etschtal und Sarntal nichts. Bei grösseren Distanzen oder Geschäftskunden mit Detail-Planung 80 €, die ich beim Auftrag wieder abziehe." },
      { q: "Garantie und Konformität?", a: "Jede Anlage wird mit Konformitätserklärung übergeben. Auf Arbeit gebe ich 2 Jahre Garantie, auf Material die Herstellergarantie (PV-Module typisch 25 Jahre Leistung)." },
    ],
    bookEyebrow: "Termin",
    bookTitle: "Termin online buchen.",
    bookSub: "Lokalaugenschein dauert meistens 30–45 Minuten. Wähl einen freien Slot, ich bestätige per Mail.",
    bookSlotLabel: "Verfügbare Zeiten",
    bookConfirm: "Termin anfragen",
    bookConfirmed: "Termin angefragt — du bekommst gleich eine Bestätigung.",
    weekdays: ["Mo", "Di", "Mi", "Do", "Fr"],
    months: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
    bookFormName: "Dein Name",
    bookFormPhone: "Telefon",
    bookFormTopic: "Worum geht's?",
    legalLabels: {
      firma: "Firma",
      sitz: "Sitz",
      mwst: "MwSt-Nr.",
      sf: "Steuernummer",
      pec: "PEC",
      mail: "E-Mail",
      tel: "Telefon",
      bank: "Bank",
      iban: "IBAN",
      sdi: "SDI / Codice Dest.",
    },
  },
  it: {
    nav: ["Servizi", "Lavori", "Chi siamo", "FAQ", "Appuntamento", "Contatti"],
    teamEyebrow: "Team",
    teamEyebrow: "Chi",
    teamTitle: "Una persona,\nun interlocutore.",
    teamSub: "Markus Unterkofler — qualificato, Maestro artigiano, sempre presente. Niente call-center, niente subappalti.",
    team: [
      { name: "Markus Unterkofler", role: "Titolare & Maestro", since: "dal 2019", phone: "+39 347 948 9636" },
    ],
    faqEyebrow: "FAQ",
    faqTitle: "Domande frequenti.",
    faqs: [
      { q: "Quanto ci mettete a rispondere?", a: "Nei giorni lavorativi rispondo entro 48 ore. Per veri casi urgenti (black-out, danno acqua + elettricità) cerco di passare lo stesso giorno — chiama direttamente." },
      { q: "Fate anche piccoli lavori?", a: "Sì — sostituire interruttori, montare una lampada, aggiungere una presa. I lavori sotto le due ore li tariffo a forfait, senza supplemento di trasferta nella Val d'Adige." },
      { q: "Come funziona un impianto fotovoltaico?", a: "1) Sopralluogo + rilievo tetto. 2) Preventivo con stima di produzione. 3) Pratiche con e-distribuzione e GSE. 4) Montaggio in 1–2 giorni. 5) Messa in servizio + app di monitoraggio. Le pratiche le faccio io." },
      { q: "Quali marchi montate?", a: "Per il PV soprattutto SunPower, Meyer Burger e inverter Fronius. Per l'elettrico Gewiss/Vimar/Bticino. Fibra standard Telmekom. Nessun lock-in — se preferisci qualcosa di specifico, dimmelo." },
      { q: "Quanto costa un sopralluogo?", a: "Per i privati in Val d'Adige e Val Sarentino è gratuito. Per distanze maggiori o aziende con progettazione di dettaglio 80 €, scalati al momento dell'incarico." },
      { q: "Garanzia e conformità?", a: "Ogni impianto viene consegnato con dichiarazione di conformità. Sul lavoro do 2 anni di garanzia, sul materiale la garanzia del produttore (moduli PV tipicamente 25 anni di resa)." },
    ],
    bookEyebrow: "Appuntamento",
    bookTitle: "Prenota online.",
    bookSub: "Il sopralluogo dura di solito 30–45 minuti. Scegli uno slot libero, ti confermo per mail.",
    bookSlotLabel: "Orari disponibili",
    bookConfirm: "Richiedi appuntamento",
    bookConfirmed: "Appuntamento richiesto — ricevi la conferma a breve.",
    weekdays: ["Lu", "Ma", "Me", "Gi", "Ve"],
    months: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
    bookFormName: "Il tuo nome",
    bookFormPhone: "Telefono",
    bookFormTopic: "Di cosa si tratta?",
    legalLabels: {
      firma: "Ragione sociale",
      sitz: "Sede",
      mwst: "P.IVA",
      sf: "Codice Fiscale",
      pec: "PEC",
      mail: "E-mail",
      tel: "Telefono",
      bank: "Banca",
      iban: "IBAN",
      sdi: "Codice Destinatario",
    },
  },
};

window.LEGAL = {
  firma: "ELEKTRIX des Unterkofler Markus",
  sitz: "39010 Mölten (BZ) · Südtirol",
  mwst: "IT 03019190218",
  sf:   "NTRMKS88E25A952F",
  pec:  "elektrix@pec.bz.it",
  mail: "info@elektrix.it",
  tel:  "+39 347 948 9636",
  bank: "Raiffeisenkasse Etschtal",
  iban: "IT 09 V 08269 58960 00030 0012092",
  sdi:  "RWDS1D5",
};

/* ----------------------------------------------------------------
   TEAM
---------------------------------------------------------------- */
function Team({ t }) {
  return (
    <section id="team" className="section section-light">
      <div className="section-head">
        <span className="mono eyebrow">— {t.teamEyebrow}</span>
        <h2 className="section-title">
          {t.teamTitle.split("\n").map((l, i) => <span key={i}>{l}<br/></span>)}
        </h2>
        <p className="section-sub">{t.teamSub}</p>
      </div>
      <div className="team-grid">
        {t.team.map((p, i) => (
          <article key={i} className="team-card">
            <div className="team-photo">
              <TeamSilhouette idx={i} />
              <span className="team-photo-tag mono">FOTO · {p.name.split(" ")[0].toUpperCase()}</span>
            </div>
            <div className="team-meta">
              <h3>{p.name}</h3>
              <span className="mono team-role">{p.role}</span>
              <div className="team-row">
                <span className="mono">{p.since}</span>
                <a href={"tel:" + p.phone.replace(/\s/g, "")}>{p.phone}</a>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

function TeamSilhouette({ idx }) {
  const tones = [
    ["#d8d6cf", "#c5f23d"],
    ["#e6e4dd", "#9bbfd9"],
    ["#d2d0c8", "#ffd84a"],
    ["#dad8d1", "#ff9b54"],
  ];
  const [bg, accent] = tones[idx % tones.length];
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice">
      <rect width="400" height="500" fill={bg} />
      <rect x="20" y="20" width="40" height="40" fill={accent} />
      {/* shoulders + head */}
      <g transform="translate(200 280)">
        <circle cx="0" cy="-90" r="78" fill="#1a1a1a" opacity="0.85" />
        <path d="M-150 220 C-150 80 -90 0 0 0 C90 0 150 80 150 220 Z" fill="#1a1a1a" opacity="0.85" />
        <rect x="-50" y="-110" width="100" height="22" fill={accent} />
      </g>
    </svg>
  );
}

/* ----------------------------------------------------------------
   FAQ
---------------------------------------------------------------- */
function FAQ({ t }) {
  const [open, setOpen] = useS(0);
  return (
    <section id="faq" className="section section-cream">
      <div className="faq-grid">
        <div className="faq-head">
          <span className="mono eyebrow">— {t.faqEyebrow}</span>
          <h2 className="section-title">{t.faqTitle}</h2>
          <p className="section-sub">
            {t.cta} → <a href="#kontakt" style={{ color: "var(--black)", borderBottom: "1.5px solid var(--lime)" }}>{t.contactEyebrow}</a>
          </p>
        </div>
        <ul className="faq-list">
          {t.faqs.map((f, i) => (
            <li key={i} className={"faq-item " + (open === i ? "is-open" : "")}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span className="mono faq-n">{String(i+1).padStart(2,"0")}</span>
                <span className="faq-qtext">{f.q}</span>
                <span className="faq-toggle">{open === i ? "–" : "+"}</span>
              </button>
              {open === i && <div className="faq-a">{f.a}</div>}
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* ----------------------------------------------------------------
   BOOKING — simple request form (no calendar, just email + phone)
---------------------------------------------------------------- */
function Booking({ t, lang }) {
  const topics = (t.topics && t.topics.length) ? t.topics : ["Elektro & Beleuchtung", "Antennentechnik", "Glasfaser", "Photovoltaik", "Etwas anderes"];
  const [form, setForm] = useS({ name: "", email: "", phone: "", topic: topics[0], when: "", message: "" });
  const [sent, setSent] = useS(false);
  const u = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const submit = (e) => {
    e.preventDefault();
    const subject = encodeURIComponent(`[ELEKTRIX-Termin] ${form.topic} · ${form.name}`);
    const lines = [
      `Name: ${form.name}`,
      `E-Mail: ${form.email}`,
      `Telefon: ${form.phone}`,
      `Bereich: ${form.topic}`,
      `Wunschtermin: ${form.when || "—"}`,
      "",
      "Worum geht's:",
      form.message,
      "",
      "— gesendet via elektrix.it",
    ];
    const body = encodeURIComponent(lines.join("\n"));
    window.location.href = `mailto:info@elektrix.it?subject=${subject}&body=${body}`;
    setSent(true);
    setTimeout(() => { setSent(false); setForm({ name: "", email: "", phone: "", topic: topics[0], when: "", message: "" }); }, 5000);
  };

  const L = lang === "it"
    ? { name: "Nome", email: "E-mail", phone: "Telefono", topic: "Area", when: "Wunschtermin", whenPh: "p.es. settimana del 12 maggio, mattina", msg: "Di cosa si tratta?", send: "Richiedi appuntamento", sent: "Grazie — ti richiamo a breve.",
        note: "Ti richiamo entro 48 ore lavorative per concordare un orario." }
    : { name: "Name", email: "E-Mail", phone: "Telefon", topic: "Bereich", when: "Wunschtermin", whenPh: "z.B. Woche vom 12. Mai, vormittags", msg: "Worum geht's?", send: "Termin anfragen", sent: "Danke — ich melde mich kurz bei dir.",
        note: "Ich rufe dich innerhalb von 48 Werktagsstunden zurück um einen Termin zu vereinbaren." };

  return (
    <section id="termin" className="section section-light section-book">
      <div className="section-head">
        <span className="mono eyebrow">— {t.bookEyebrow}</span>
        <h2 className="section-title">{t.bookTitle}</h2>
        <p className="section-sub">{t.bookSub}</p>
      </div>

      <div className="termin-grid">
        <div className="termin-side">
          <ol className="termin-steps">
            <li><span className="mono">01</span><div><strong>{lang === "it" ? "Form ausfüllen" : "Formular ausfüllen"}</strong><p>{lang === "it" ? "Nome, telefono e cosa serve — bastano pochi minuti." : "Name, Telefon und worum es geht — dauert keine 2 Minuten."}</p></div></li>
            <li><span className="mono">02</span><div><strong>{lang === "it" ? "Richiamo" : "Rückruf"}</strong><p>{L.note}</p></div></li>
            <li><span className="mono">03</span><div><strong>{lang === "it" ? "Appuntamento concordato" : "Termin fix"}</strong><p>{lang === "it" ? "Concordiamo data e ora che funzionano per entrambi." : "Wir vereinbaren Datum und Uhrzeit die bei beiden passen."}</p></div></li>
          </ol>

          <div className="termin-direct">
            <span className="mono">{lang === "it" ? "OPPURE DIRETTAMENTE" : "ODER DIREKT"}</span>
            <a href="tel:+393479489636" className="termin-direct-row">
              <strong>+39 347 948 9636</strong>
              <span className="mono">{lang === "it" ? "TELEFONO" : "TELEFON"}</span>
            </a>
            <a href="mailto:info@elektrix.it" className="termin-direct-row">
              <strong>info@elektrix.it</strong>
              <span className="mono">E-MAIL</span>
            </a>
          </div>
        </div>

        <form className="termin-form" onSubmit={submit}>
          <div className="field">
            <label className="mono">{L.name}</label>
            <input required value={form.name} onChange={u("name")} placeholder="Markus Mustermann" />
          </div>
          <div className="field-row">
            <div className="field">
              <label className="mono">{L.email}</label>
              <input required type="email" value={form.email} onChange={u("email")} placeholder="name@beispiel.it" />
            </div>
            <div className="field">
              <label className="mono">{L.phone} *</label>
              <input required value={form.phone} onChange={u("phone")} placeholder="+39 …" />
            </div>
          </div>
          <div className="field">
            <label className="mono">{L.topic}</label>
            <div className="topic-grid">
              {topics.map((tp) =>
                <button key={tp} type="button"
                  className={"topic " + (form.topic === tp ? "is-on" : "")}
                  onClick={() => setForm((f) => ({ ...f, topic: tp }))}>
                  {tp}
                </button>
              )}
            </div>
          </div>
          <div className="field">
            <label className="mono">{L.when}</label>
            <input value={form.when} onChange={u("when")} placeholder={L.whenPh} />
          </div>
          <div className="field">
            <label className="mono">{L.msg}</label>
            <textarea required rows="4" value={form.message} onChange={u("message")} placeholder="…" />
          </div>
          <div className="field consent-field">
            <label className="consent-row">
              <input required type="checkbox" />
              <span>{lang === "it"
                ? <>Ho letto l'<a href="datenschutz.html">informativa privacy</a> e acconsento al trattamento dei dati per la richiesta di appuntamento.</>
                : <>Ich habe die <a href="datenschutz.html">Datenschutzerklärung</a> gelesen und willige in die Verarbeitung meiner Daten für die Terminanfrage ein.</>}</span>
            </label>
          </div>
          <button type="submit" className="btn btn-primary btn-full">
            {sent ? L.sent : L.send}
          </button>
        </form>
      </div>
    </section>
  );
}

window.Team = Team;
window.FAQ = FAQ;
window.Booking = Booking;
