// Main app — orchestrates the page + Tweaks panel.

const THEMES = [
  { key: "electric", label: "Electric", colors: ["#0a0a0a", "#d4ff3f", "#ffffff"] },
  { key: "violet",   label: "Violet",   colors: ["#0d0a1f", "#b58cff", "#f3edff"] },
  { key: "coral",    label: "Coral",    colors: ["#faf6f1", "#ff5d3c", "#181410"] },
  { key: "mint",     label: "Mint",     colors: ["#f6f8f4", "#0d6b4f", "#0c1612"] },
];

function ThemeChips({ value, onChange }) {
  return (
    <TweakRow label="Color theme">
      <div className="twk-chips" role="radiogroup">
        {THEMES.map(th => {
          const [hero, ...rest] = th.colors;
          const on = th.key === value;
          return (
            <button key={th.key} type="button" className="twk-chip" role="radio"
                    aria-checked={on} data-on={on ? "1" : "0"}
                    aria-label={th.label} title={th.label}
                    style={{ background: hero }}
                    onClick={() => onChange(th.key)}>
              <span>
                {rest.map((c, j) => <i key={j} style={{ background: c }} />)}
              </span>
            </button>
          );
        })}
      </div>
    </TweakRow>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "coral",
  "font": "modern",
  "hero": "score",
  "badge": "pill",
  "layout": "masonry"
}/*EDITMODE-END*/;

const REVIEWS = window.REVIEWS;
const SOURCES = window.SOURCES;
const AGGREGATE = window.AGGREGATE;
const TRUSTPILOT_URL = "https://www.trustpilot.com/review/www.e-ita.org";

// FAQ content — also mirrored in the FAQPage JSON-LD in index.html. If you
// edit one, edit the other so the structured data matches the visible page
// (Google flags mismatches between visible and JSON-LD FAQ content).
// Answers are grounded in the actual review dataset — see the cited
// review IDs in comments. Do not invent.
const FAQ_ITEMS = [
  {
    q: "Is E-ITA legit?",
    a: "E-ITA (e-ita.org) holds a 4.3-star TrustScore on Trustpilot from 1,369 verified reviews. The majority of reviewers report that their international driving permit was issued quickly and accepted at car rental counters and roadside checkpoints. A minority report negative experiences, mostly around delivery times — see the negative-review summary below.",
  },
  {
    q: "What is E-ITA's Trustpilot rating?",
    a: "As of 28 May 2026, E-ITA's TrustScore on Trustpilot is 4.3 out of 5, based on 1,369 reviews. 77% of reviewers gave 5 stars and 12% gave 1 star. These numbers are mirrored directly from E-ITA's public Trustpilot profile and refreshed monthly.",
  },
  {
    q: "How long does E-ITA take to deliver an IDP?",
    a: "Reviewers consistently describe the digital PDF as arriving within hours of order. The physical card and booklet ship by mail and reviewers report delivery within roughly 5 to 14 days depending on country, with longer waits to remote addresses. E-ITA offers both standard and express options; actual delivery times can vary.",
  },
  {
    q: "Is the E-ITA international driving permit accepted by car rental companies?",
    a: "Multiple verified reviewers report successfully using the E-ITA permit at rental counters and police checkpoints in Italy, Spain, Iceland, Japan, Mexico, Thailand, and elsewhere. One reviewer noted uncertainty about whether it is legal in Vietnam specifically. Whether a permit is accepted depends on the rental company and the country's regulations.",
  },
  {
    q: "What do negative E-ITA reviews say?",
    a: "The 1- and 2-star reviews on Trustpilot most commonly cite delivery delays — especially when reviewers paid for express or overnight shipping and the package arrived several days late — and difficulty reaching customer support before issues are escalated. A small number of reviewers report not receiving their physical license at all. These complaints are present in the dataset alongside the positive reviews.",
  },
];

function AboutSection() {
  return (
    <section className="prose" id="about">
      <h2>About E-ITA reviews on Trustpilot</h2>
      <p>
        EITA Reviews is an independent, manually curated mirror of <a href={TRUSTPILOT_URL} target="_blank" rel="noreferrer">E-ITA's public Trustpilot profile</a>. E-ITA, at <a href="https://www.e-ita.org" target="_blank" rel="noreferrer">e-ita.org</a>, is an online international driving permit service.
      </p>
      <p>
        The aggregate score and review count shown on this page — <strong>{AGGREGATE.score.toFixed(1)}★ from {AGGREGATE.total.toLocaleString()} reviews</strong> — are taken directly from Trustpilot's own profile page and refreshed monthly. The individual E-ITA reviews displayed below are a curated selection from that same Trustpilot profile, with the original text preserved verbatim including any typos.
      </p>
      <p>
        This page is not affiliated with E-ITA or Trustpilot. For the canonical, unfiltered view of every review, follow the Trustpilot link. Last updated <time dateTime={AGGREGATE.lastUpdated}>{formatDate(AGGREGATE.lastUpdated)}</time>.
      </p>
    </section>
  );
}

function FaqSection() {
  return (
    <section className="prose" id="faq">
      <h2>Frequently asked questions about E-ITA</h2>
      {FAQ_ITEMS.map((item, i) => (
        <div key={i} className="faq-item">
          <h3>{item.q}</h3>
          <p>{item.a}</p>
        </div>
      ))}
    </section>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [filter, setFilter] = React.useState("all");
  const [sort, setSort] = React.useState("newest");

  // Sync theme + font to <html> for CSS var swap
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.theme);
    document.documentElement.setAttribute("data-font", t.font);
  }, [t.theme, t.font]);

  const counts = React.useMemo(() => {
    const c = {};
    for (const r of REVIEWS) c[r.source] = (c[r.source] || 0) + 1;
    return c;
  }, []);

  const visible = React.useMemo(() => {
    let arr = filter === "all" ? REVIEWS.slice() : REVIEWS.filter(r => r.source === filter);
    arr.sort((a, b) => {
      switch (sort) {
        case "oldest": return a.date.localeCompare(b.date);
        case "rating-high": return b.rating - a.rating || b.date.localeCompare(a.date);
        case "rating-low": return a.rating - b.rating || b.date.localeCompare(a.date);
        default: return b.date.localeCompare(a.date);
      }
    });
    return arr;
  }, [filter, sort]);

  const renderHero = () => {
    if (t.hero === "quote") return <HeroQuote reviews={REVIEWS} badgeStyle={t.badge} />;
    if (t.hero === "stats") return <HeroStats badgeStyle={t.badge} />;
    return <HeroScore badgeStyle={t.badge} />;
  };

  const renderLayout = () => {
    if (t.layout === "grid") {
      return (
        <div className="layout-grid">
          {visible.map(r => <ReviewCard key={r.id} review={r} badgeStyle={t.badge} />)}
        </div>
      );
    }
    if (t.layout === "feed") {
      return (
        <div className="layout-feed">
          {visible.map(r => <ReviewCard key={r.id} review={r} badgeStyle={t.badge} variant="feed" />)}
        </div>
      );
    }
    if (t.layout === "list") {
      return (
        <div className="layout-list">
          {visible.map(r => <ListRow key={r.id} review={r} badgeStyle={t.badge} />)}
        </div>
      );
    }
    return (
      <div className="layout-masonry">
        {visible.map(r => <ReviewCard key={r.id} review={r} badgeStyle={t.badge} />)}
      </div>
    );
  };

  return (
    <>
      <div className="shell">
        <header className="nav">
          <div className="nav-brand">
            <span className="dot"></span>
            eitareviews<span style={{ color: "var(--ink-3)" }}>.com</span>
          </div>
          <nav className="nav-meta">
            <a href="#reviews">Reviews</a>
            <a href="#about">About</a>
            <a href="#faq">FAQ</a>
            <a href="https://e-ita.org" target="_blank" rel="noreferrer">e-ita.org ↗</a>
          </nav>
          <button className="nav-cta" onClick={() => window.open("https://e-ita.org", "_blank")}>
            Get your IDP →
          </button>
        </header>

        {renderHero()}

        <div className="section-head" id="reviews">
          <div className="left">
            <span className="eyebrow"><span className="bar" />SELECTED REVIEWS</span>
            <h2>What people are saying.</h2>
            <div className="count">
              Showing {visible.length} selected reviews of {AGGREGATE.total.toLocaleString()} on Trustpilot · sorted by {sort.replace("-", " ")}
            </div>
          </div>
        </div>

        <FilterBar
          active={filter} onChange={setFilter}
          sort={sort} onSort={setSort}
          counts={counts}
          layout={t.layout} onLayout={v => setTweak("layout", v)}
        />

        {renderLayout()}

        <AboutSection />
        <FaqSection />

        <footer className="foot">
          <div>© 2026 eitareviews.com — curated mirror of E-ITA's public Trustpilot profile · last updated {formatDate(AGGREGATE.lastUpdated)}</div>
          <div style={{ display: "flex", gap: 24 }}>
            <a href="#about">About</a>
            <a href="#faq">FAQ</a>
            <a href={TRUSTPILOT_URL} target="_blank" rel="noreferrer">View on Trustpilot ↗</a>
            <a href="https://e-ita.org" target="_blank" rel="noreferrer">Visit e-ita.org ↗</a>
          </div>
        </footer>
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme" />
        <ThemeChips value={t.theme} onChange={v => setTweak("theme", v)} />

        <TweakSection label="Typography" />
        <TweakSelect
          label="Font pairing"
          value={t.font}
          options={[
            { value: "modern",     label: "Modern · Geist" },
            { value: "editorial",  label: "Editorial · Instrument Serif" },
            { value: "techno",     label: "Techno · Space Grotesk" },
            { value: "industrial", label: "Industrial · Archivo" },
          ]}
          onChange={v => setTweak("font", v)}
        />

        <TweakSection label="Layout" />
        <TweakSelect
          label="Hero layout"
          value={t.hero}
          options={[
            { value: "score", label: "Aggregate score" },
            { value: "quote", label: "Quote carousel" },
            { value: "stats", label: "Stats grid" },
          ]}
          onChange={v => setTweak("hero", v)}
        />
        <TweakSelect
          label="Reviews layout"
          value={t.layout}
          options={[
            { value: "masonry", label: "Masonry" },
            { value: "grid",    label: "Uniform grid" },
            { value: "feed",    label: "Single column feed" },
            { value: "list",    label: "Dense list" },
          ]}
          onChange={v => setTweak("layout", v)}
        />

        <TweakSection label="Source badges" />
        <TweakRadio
          label="Style"
          value={t.badge}
          options={[
            { value: "pill",    label: "Pill" },
            { value: "outline", label: "Outline" },
            { value: "minimal", label: "Minimal" },
            { value: "dot",     label: "Dot" },
          ]}
          onChange={v => setTweak("badge", v)}
        />
      </TweaksPanel>
    </>
  );
}

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