// Localization Hub — i18n key management
// Side-by-side table per namespace, locale columns, machine-suggest, status flags.

const { useState, useRef } = React;

const LOC_NAMESPACES = [
  { id: "welcome",  label: "welcome",  count: 24, warn: false, active: true },
  { id: "billing",  label: "billing",  count: 18, warn: false },
  { id: "auth",     label: "auth",     count: 11, warn: true },
  { id: "footer",   label: "footer",   count: 9,  warn: false },
  { id: "retention",label: "retention",count: 16, warn: true },
  { id: "marketing",label: "marketing",count: 7,  warn: false },
  { id: "legal",    label: "legal",    count: 4,  warn: false },
];

const LOC_LOCALES = [
  { code: "en", name: "English",  region: "en-US", progress: 100, isDefault: true },
  { code: "fr", name: "Français", region: "fr-FR", progress: 96 },
  { code: "de", name: "Deutsch",  region: "de-DE", progress: 88 },
  { code: "es", name: "Español",  region: "es-ES", progress: 72 },
  { code: "ja", name: "日本語",    region: "ja-JP", progress: 41 },
];

// Each row is a translation key. Per locale fields: text | empty | stale
const LOC_ROWS = [
  {
    key: "welcome.hero.eyebrow",
    note: "Eyebrow above hero title",
    type: "Plain",
    values: {
      en: { text: "Welcome aboard" },
      fr: { text: "Bienvenue à bord" },
      de: { text: "Willkommen an Bord" },
      es: { text: "Bienvenido a bordo" },
      ja: { text: "ようこそ" },
    },
  },
  {
    key: "welcome.hero.title",
    note: "Hero title · 1 variable",
    type: "Templated",
    values: {
      en: { text: "You're on the Pro plan, ", parts: ["You're on the Pro plan, ", { ph: "{{firstName}}" }, "."] },
      fr: { text: "Vous êtes sur le plan Pro, ", parts: ["Vous êtes sur le plan Pro, ", { ph: "{{firstName}}" }, "."] },
      de: { text: "Du bist im Pro-Plan, ", parts: ["Du bist im Pro-Plan, ", { ph: "{{firstName}}" }, "."] },
      es: { text: "", parts: [] },
      ja: { text: "", parts: [] },
    },
  },
  {
    key: "welcome.hero.body",
    note: "Hero supporting paragraph",
    type: "Plain",
    values: {
      en: { text: "Everything you need to ship better email — drag-and-drop authoring, native multilingual variants, dark mode and one-click ZIP export." },
      fr: { text: "Tout ce qu'il faut pour envoyer de meilleurs emails — édition glisser-déposer, variantes multilingues natives, mode sombre et export ZIP en un clic." },
      de: { text: "Alles, was du brauchst, um bessere E-Mails zu versenden — Drag-and-Drop, native mehrsprachige Varianten, Dark Mode und ZIP-Export per Klick.", stale: true },
      es: { text: "" },
      ja: { text: "" },
    },
  },
  {
    key: "welcome.cta.label",
    note: "Hero CTA · used 3× in template",
    type: "Plain",
    values: {
      en: { text: "Open the composer" },
      fr: { text: "Ouvrir l'éditeur" },
      de: { text: "Editor öffnen" },
      es: { text: "Abrir el editor" },
      ja: { text: "" },
    },
  },
  {
    key: "welcome.cta.subline",
    note: "Below CTA, italics",
    type: "Plain",
    values: {
      en: { text: "Takes about 90 seconds." },
      fr: { text: "Environ 90 secondes." },
      de: { text: "Etwa 90 Sekunden." },
      es: { text: "Aproximadamente 90 segundos." },
      ja: { text: "" },
    },
  },
  {
    key: "welcome.cards.1.title",
    note: "Feature card · drag-drop",
    type: "Plain",
    values: {
      en: { text: "Drag & drop authoring" },
      fr: { text: "Édition glisser-déposer" },
      de: { text: "Drag-and-Drop-Bearbeitung" },
      es: { text: "Edición arrastrar y soltar" },
      ja: { text: "" },
    },
  },
  {
    key: "welcome.cards.1.body",
    note: "Feature card · drag-drop body",
    type: "Plain",
    values: {
      en: { text: "Build real, table-based email — no markup gymnastics." },
      fr: { text: "Composez des emails réels en tableaux — sans gymnastique de balises." },
      de: { text: "" },
      es: { text: "" },
      ja: { text: "" },
    },
  },
  {
    key: "welcome.cards.2.title",
    note: "Feature card · multilingual",
    type: "Plain",
    values: {
      en: { text: "Native multilingual" },
      fr: { text: "Multilingue natif" },
      de: { text: "Native Mehrsprachigkeit" },
      es: { text: "Multilingüe nativo" },
      ja: { text: "ネイティブ多言語対応" },
    },
  },
  {
    key: "welcome.cards.3.title",
    note: "Feature card · dark mode",
    type: "Plain",
    values: {
      en: { text: "Dark mode, done right" },
      fr: { text: "Mode sombre, comme il faut" },
      de: { text: "Dark Mode — richtig gemacht" },
      es: { text: "" },
      ja: { text: "" },
    },
  },
  {
    key: "welcome.footer.unsubscribe",
    note: "Required by US CAN-SPAM",
    type: "Plain",
    values: {
      en: { text: "Unsubscribe from these emails" },
      fr: { text: "Se désabonner de ces emails" },
      de: { text: "Von diesen E-Mails abmelden" },
      es: { text: "Cancelar la suscripción" },
      ja: { text: "メール配信を停止する" },
    },
  },
  {
    key: "welcome.footer.address",
    note: "Required postal address",
    type: "Plain",
    values: {
      en: { text: "Acme Inc · 2 Pine Street, San Francisco CA 94111" },
      fr: { text: "Acme Inc · 2 Pine Street, San Francisco CA 94111" },
      de: { text: "Acme Inc · 2 Pine Street, San Francisco CA 94111" },
      es: { text: "Acme Inc · 2 Pine Street, San Francisco CA 94111" },
      ja: { text: "Acme Inc · 2 Pine Street, San Francisco CA 94111" },
    },
  },
];

const LocCell = ({ v, locale, isActive, rowKey, onEdit }) => {
  const ref = useRef(null);
  if (!v || !v.text) {
    return (
      <div className="loc-cell">
        <span className="loc-cell-empty">
          <span className="miss-label">
            <Icon name="warn" size={11} /> Missing copy
          </span>
          <button className="machine-suggest" onClick={() => onEdit?.(rowKey, locale)}>
            <Icon name="sparkle" size={11} />
            Suggest from EN
          </button>
        </span>
      </div>
    );
  }
  return (
    <div className={`loc-cell${v.stale ? " is-stale" : ""}`} onClick={() => onEdit?.(rowKey, locale)}>
      <div className="loc-cell-text">
        {v.parts ? v.parts.map((p, i) => (
          typeof p === "string"
            ? <span key={i}>{p}</span>
            : <span key={i} className="ph">{p.ph}</span>
        )) : v.text}
      </div>
      {v.stale && (
        <div className="loc-cell-flag">
          <Icon name="warn" size={10} /> Source updated — review
        </div>
      )}
    </div>
  );
};

const LocalizationView = () => {
  const [namespace, setNamespace] = useState("welcome");
  const [activeRow, setActiveRow] = useState("welcome.hero.title");
  const [editing, setEditing] = useState(null); // {row, locale}

  return (
    <div className="loc">
      <aside className="loc-side">
        <h3>Templates</h3>
        <button className="loc-namespace is-active">
          <Icon name="mail" size={13} />
          <span>Welcome — Pro plan</span>
          <span className="count">v14</span>
        </button>

        <h3>Namespaces</h3>
        {LOC_NAMESPACES.map(ns => (
          <button
            key={ns.id}
            className={`loc-namespace${ns.id === namespace ? " is-active" : ""}`}
            onClick={() => setNamespace(ns.id)}
          >
            <Icon name="code" size={13} />
            <span>{ns.label}</span>
            {ns.warn ? <span className="warn-dot" title="Missing translations" /> : <span className="count">{ns.count}</span>}
          </button>
        ))}

        <h3>Glossary</h3>
        <button className="loc-namespace">
          <Icon name="star" size={13} />
          <span>Brand voice</span>
          <span className="count">28</span>
        </button>
        <button className="loc-namespace">
          <Icon name="settings" size={13} />
          <span>Do-not-translate</span>
          <span className="count">12</span>
        </button>
      </aside>

      <section className="loc-main">
        <header className="loc-head">
          <div className="titles">
            <div className="loc-eyebrow">Localization</div>
            <div className="loc-h1">
              <span>Welcome — Pro plan</span>
              <code>{`{{${namespace}.*}}`}</code>
            </div>
            <div className="loc-sub">
              {LOC_ROWS.length} keys · 5 locales · source language English (en-US) · last sync 4 min ago
            </div>
          </div>
          <Button variant="ghost" iconLeft="download">Export PO</Button>
          <Button variant="secondary" iconLeft="globe">Add locale</Button>
          <Button variant="primary" iconLeft="check">Mark all reviewed</Button>
        </header>

        <div className="loc-locale-bar">
          {LOC_LOCALES.map(l => (
            <button key={l.code} className={`loc-locale-chip${l.isDefault ? " is-default" : ""}`}>
              <span className="flag-sm" style={l.isDefault ? null : null}>
                <span style={{ fontSize: 8 }}>{l.code.toUpperCase()}</span>
              </span>
              <span>{l.name}</span>
              <span className="mini-track"><div style={{ width: `${l.progress}%` }} /></span>
              <span className="progress">{l.progress}%</span>
            </button>
          ))}
          <div style={{ flex: 1 }} />
          <button className="filter-chip">
            <Icon name="warn" size={12} /> Show only missing
          </button>
          <button className="filter-chip">
            <Icon name="settings" size={12} /> Tools
          </button>
        </div>

        <div className="loc-table-wrap">
          <table className="loc-table">
            <thead>
              <tr>
                <th className="col-key">Key</th>
                {LOC_LOCALES.map(l => (
                  <th key={l.code}>
                    <div className="locale-head">
                      <span className={`flag-sm${l.isDefault ? " is-default" : ""}`}>{l.code.toUpperCase()}</span>
                      <span>{l.name}</span>
                      <span className="pc">{l.progress}%</span>
                    </div>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {LOC_ROWS.map(r => (
                <tr key={r.key}
                    className={activeRow === r.key ? "is-active" : ""}
                    onClick={() => setActiveRow(r.key)}>
                  <td className={`col-key${activeRow === r.key ? " is-active" : ""}`}>
                    <span className="loc-key-token">{`{{${r.key}}}`}</span>
                    <div className="loc-key-meta">
                      <span>{r.type}</span>
                      <span style={{ color: "var(--fg-4)" }}>·</span>
                      <span>{r.note}</span>
                    </div>
                  </td>
                  {LOC_LOCALES.map(l => (
                    <td key={l.code}>
                      <LocCell
                        v={r.values[l.code]}
                        locale={l.code}
                        rowKey={r.key}
                        isActive={editing?.row === r.key && editing?.locale === l.code}
                        onEdit={(rk, lc) => setEditing({ row: rk, locale: lc })}
                      />
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { LocalizationView });
