/* GENT email automations — preview shell.
   Dropdown to switch automations + segmented toggle for A/B variants.
   Selection persists in localStorage. */

const { useState, useEffect, useRef } = React;
const EMAILS = window.GentEmails;

const LS_EMAIL = "gent.emails.selected";
const LS_VARIANT = "gent.emails.variant"; // JSON map of {emailId: variantKey}

function useIcons(dep) {
  useEffect(() => {
    const t = setTimeout(() => window.lucide && window.lucide.createIcons(), 30);
    return () => clearTimeout(t);
  }, [dep]);
}

function App() {
  const [id, setId] = useState(() => localStorage.getItem(LS_EMAIL) || EMAILS[0].id);
  const [variants, setVariants] = useState(() => {
    try { return JSON.parse(localStorage.getItem(LS_VARIANT)) || {}; } catch (e) { return {}; }
  });

  const email = EMAILS.find((e) => e.id === id) || EMAILS[0];
  const variant = email.variants ? (variants[email.id] || email.variants[0].key) : null;

  useEffect(() => { localStorage.setItem(LS_EMAIL, id); }, [id]);
  useEffect(() => { localStorage.setItem(LS_VARIANT, JSON.stringify(variants)); }, [variants]);

  // Re-render Lucide icons whenever the visible email or variant changes.
  useIcons(id + "|" + variant);

  const setVariant = (key) => setVariants((v) => ({ ...v, [email.id]: key }));

  // Grouped options for the select.
  const groups = [];
  EMAILS.forEach((e) => {
    let g = groups.find((x) => x.name === e.group);
    if (!g) { g = { name: e.group, items: [] }; groups.push(g); }
    g.items.push(e);
  });

  const subject = email.subjects ? email.subjects[variant] : email.subject;
  const preheader = email.preheaders ? email.preheaders[variant] : email.preheader;
  const Component = email.Component;

  return (
    <div className="app">
      <div className="topbar">
        <div className="brand">
          <img src="assets/logos/gent-logo-white.png" alt="GENT" />
          <span className="divider"></span>
          <span className="label">Email Automations</span>
        </div>

        <div className="controls">
          <div className="field">
            <span className="flabel">Automation</span>
            <div className="select-wrap">
              <select value={id} onChange={(e) => setId(e.target.value)}>
                {groups.map((g) => (
                  <optgroup label={g.name} key={g.name}>
                    {g.items.map((e) => <option value={e.id} key={e.id}>{e.name}</option>)}
                  </optgroup>
                ))}
              </select>
              <i data-lucide="chevron-down" className="chev"></i>
            </div>
          </div>

          {email.variants && (
            <div className="segmented">
              <span className="flabel">Variation</span>
              <div className="seg">
                {email.variants.map((v) => (
                  <button key={v.key} aria-pressed={variant === v.key} onClick={() => setVariant(v.key)}>
                    {v.label}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="workspace">
        <aside className="sidebar">
          <p className="s-kicker">{email.group}</p>
          <h2 className="s-name">{email.name}</h2>
          <span className="trigger"><i data-lucide="zap" style={{ width: 12, height: 12 }}></i> {email.trigger}</span>
          <div className="metaline"><span className="k">From</span><span className="v">{email.from}</span></div>
          <div className="metaline"><span className="k">Subject line</span><span className="v subject">{subject}</span></div>
          <div className="metaline"><span className="k">Preview text</span><span className="v pre">{preheader}</span></div>
          <p className="s-hint"><i data-lucide="mouse-pointer-2"></i> Scroll the email on the right to preview the full message.</p>
        </aside>

        <div className="stage">
          <div className={"email-shell host-type" + ((id === "welcome" || id === "cart4" || id === "cart24" || id === "thankyou") ? " welcome-hero" : "") + (id === "cart4" ? " cart4-hero" : "") + (id === "cart24" ? " cart24-hero" : "") + (id === "thankyou" ? " thankyou-hero" : "") + (id === "winback" ? " winback-hero" : "")} key={id + variant}>
            <Component variant={variant} />
          </div>
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("gent-app")).render(<App />);
