// OneDoor marketing site — shared components
// All components are attached to window at the bottom for cross-script scope.

const { useState, useEffect, useRef } = React;

/* ============ AURORA BACKDROP ============ */
function Aurora({ variant = "default", className = "" }) {
  const variants = {
    default: {
      bg: "radial-gradient(60% 80% at 15% 25%, #F5B84A 0%, #F07A3C 22%, #E24A5C 42%, #6B4BC7 70%, #1A0F2E 100%)",
    },
    wave: {
      // mimics the real brand wordmark artwork
      bg: "linear-gradient(100deg, #0B0714 0%, #1A0F2E 48%, #2A1652 52%, #3B3585 100%)",
    },
    dusk: {
      bg: "radial-gradient(70% 90% at 80% 80%, #6B4BC7 0%, #3B3585 45%, #120A22 80%)",
    },
  };
  const v = variants[variant] || variants.default;
  return (
    <div className={`od-aurora ${className}`} aria-hidden="true" style={{ background: v.bg }}>
      <div className="od-aurora-grain" />
    </div>
  );
}

/* ============ WORDMARK ============ */
function Wordmark({ size = 28 }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <img src="assets/onedoor-icon.png" alt="" width={size + 4} height={size + 4}
        style={{ borderRadius: 8, display: "block" }} />
      <span style={{
        fontFamily: "Sora, sans-serif", fontWeight: 700, fontSize: size * 0.75,
        letterSpacing: "-0.02em", color: "#F5F1FF",
      }}>OneDoor</span>
    </div>
  );
}

/* ============ BUTTON ============ */
function Button({ variant = "primary", children, as: As = "button", className = "", ...props }) {
  return (
    <As className={`od-btn od-btn-${variant} ${className}`} {...props}>{children}</As>
  );
}

/* ============ PILL / TAG ============ */
function Pill({ tone = "muted", children, dot = false }) {
  return (
    <span className={`od-pill od-pill-${tone}`}>
      {dot && <span className="od-pill-dot" />}
      {children}
    </span>
  );
}

/* ============ SECTION WRAPPER ============ */
function Section({ id, eyebrow, title, subtitle, children, align = "left" }) {
  return (
    <section id={id} className={`od-section od-align-${align}`}>
      <div className="od-section-head">
        {eyebrow && <div className="od-eyebrow">{eyebrow}</div>}
        {title && <h2 className="od-h2">{title}</h2>}
        {subtitle && <p className="od-subtitle">{subtitle}</p>}
      </div>
      {children}
    </section>
  );
}

/* ============ PHONE FRAME ============ */
function Phone({ children, tilt = 0, accent = false }) {
  return (
    <div className={`od-phone-wrap ${accent ? "od-phone-accent" : ""}`} style={{ transform: `rotate(${tilt}deg)` }}>
      <div className="od-phone">
        <div className="od-phone-notch" />
        <div className="od-phone-screen">
          <div className="od-status-bar">
            <span>9:41</span>
            <span className="od-status-icons">
              <svg width="16" height="11" viewBox="0 0 16 11" fill="none"><path d="M1 8h2v2H1zM5 6h2v4H5zM9 4h2v6H9zM13 2h2v8h-2z" fill="#F5F1FF"/></svg>
              <svg width="16" height="11" viewBox="0 0 24 24" fill="none" stroke="#F5F1FF" strokeWidth="2"><path d="M5 13a10 10 0 0 1 14 0M8.5 16.5a5 5 0 0 1 7 0M2 8.82a15 15 0 0 1 20 0" strokeLinecap="round"/><circle cx="12" cy="20" r="1" fill="#F5F1FF"/></svg>
              <svg width="24" height="11" viewBox="0 0 24 11" fill="none"><rect x="1" y="1" width="20" height="9" rx="2" stroke="#F5F1FF" strokeWidth="1" fill="none"/><rect x="3" y="3" width="16" height="5" rx="1" fill="#F5F1FF"/></svg>
            </span>
          </div>
          {children}
        </div>
      </div>
    </div>
  );
}

/* ============ APP SCREEN MOCKS ============ */
function HomeScreen() {
  return (
    <div className="od-app">
      <div className="od-app-eyebrow">ONEDOOR · PARADISE PALMS</div>
      <div className="od-app-greet">Good evening,<br/>Alex</div>
      <div className="od-app-meta">Unit 101 · 24 neighbours</div>

      <div className="od-hero-card">
        <div className="od-hero-card-inner">
          <div className="od-app-label">HOME HEALTH</div>
          <div className="od-hero-headline">On&nbsp;Track</div>
          <div className="od-ring-row">
            <div className="od-ring"><span>92</span></div>
            <div className="od-ring-meta">
              Dues current<br/>
              3 repairs done<br/>
              1 vote open
            </div>
          </div>
          <div className="od-pill-row">
            <span className="od-pill od-pill-ok"><span className="od-pill-dot"/>No issues</span>
            <span className="od-pill od-pill-info">Dues May 1</span>
          </div>
        </div>
      </div>

      <div className="od-tile-grid">
        <div className="od-tile">
          <div className="od-tile-ico" style={{color:"#7FB0FF"}}>◧</div>
          <div className="od-tile-lab">Payments</div>
          <div className="od-tile-sub">Auto-pay on</div>
        </div>
        <div className="od-tile">
          <div className="od-tile-ico" style={{color:"#F17A8A"}}>◉</div>
          <div className="od-tile-lab">Messages</div>
          <div className="od-tile-sub">1 unread</div>
        </div>
        <div className="od-tile">
          <div className="od-tile-ico" style={{color:"#4BD6A8"}}>▤</div>
          <div className="od-tile-lab">Docs</div>
          <div className="od-tile-sub">Up to date</div>
        </div>
        <div className="od-tile">
          <div className="od-tile-ico" style={{color:"#F3C46B"}}>◎</div>
          <div className="od-tile-lab">Service</div>
          <div className="od-tile-sub">2 open</div>
        </div>
      </div>

      <div className="od-app-tabbar">
        <div className="od-tab od-tab-active">Home</div>
        <div className="od-tab">Pay</div>
        <div className="od-tab">Docs</div>
        <div className="od-tab">Service</div>
        <div className="od-tab">Msgs</div>
      </div>
    </div>
  );
}

function PaymentsScreen() {
  return (
    <div className="od-app">
      <div className="od-app-eyebrow">PAYMENTS</div>
      <div className="od-app-greet" style={{fontSize:22}}>Next charge<br/>May 1</div>

      <div className="od-hero-card">
        <div className="od-hero-card-inner">
          <div className="od-app-label">MONTHLY DUES</div>
          <div className="od-big-amount">$450.00</div>
          <div className="od-pill-row">
            <span className="od-pill od-pill-ok"><span className="od-pill-dot"/>Auto-pay on</span>
          </div>
          <button className="od-btn od-btn-gradient" style={{width:"100%", justifyContent:"center", marginTop:14}}>Pay Now</button>
        </div>
      </div>

      <div className="od-app-label" style={{marginTop:18}}>RECENT</div>
      {[
        ["April dues","Apr 1 · Paid","$450","#4BD6A8"],
        ["Pool assessment","Mar 15 · Paid","$120","#4BD6A8"],
        ["March dues","Mar 1 · Paid","$450","#4BD6A8"],
      ].map(([t,s,a,c],i)=>(
        <div className="od-list-row" key={i}>
          <div>
            <div className="od-list-t">{t}</div>
            <div className="od-list-s">{s}</div>
          </div>
          <div style={{color:c, fontWeight:600, fontSize:13}}>{a}</div>
        </div>
      ))}

      <div className="od-app-tabbar">
        <div className="od-tab">Home</div>
        <div className="od-tab od-tab-active">Pay</div>
        <div className="od-tab">Docs</div>
        <div className="od-tab">Service</div>
        <div className="od-tab">Msgs</div>
      </div>
    </div>
  );
}

function BoardScreen() {
  return (
    <div className="od-app">
      <div className="od-app-eyebrow">BOARD · PARADISE PALMS</div>
      <div className="od-app-greet" style={{fontSize:22}}>Vote open</div>
      <div className="od-app-meta">Pool fence assessment · ends Fri</div>

      <div className="od-hero-card">
        <div className="od-hero-card-inner">
          <div className="od-app-label">LIVE VOTE · 18 / 24 VOTED</div>
          <div className="od-vote-title">Approve $3,200 pool fence repair?</div>
          <div className="od-vote-bar">
            <div className="od-vote-yes" style={{width:"67%"}}><span>Yes · 16</span></div>
            <div className="od-vote-no" style={{width:"33%"}}><span>No · 2</span></div>
          </div>
          <div className="od-vote-meta">Quorum reached · closes Apr 26 5pm</div>
          <div style={{display:"flex", gap:8, marginTop:12}}>
            <button className="od-btn od-btn-primary" style={{flex:1, justifyContent:"center", fontSize:13}}>Cast vote</button>
            <button className="od-btn od-btn-ghost" style={{flex:1, justifyContent:"center", fontSize:13}}>View docs</button>
          </div>
        </div>
      </div>

      <div className="od-app-label" style={{marginTop:18}}>NEEDS REVIEW</div>
      <div className="od-needs-row">
        <div>
          <div className="od-list-t">Leaky faucet · Unit 101</div>
          <div className="od-list-s">Opened 2d ago</div>
        </div>
        <span className="od-pill od-pill-warn">Review</span>
      </div>

      <div className="od-app-tabbar">
        <div className="od-tab">Home</div>
        <div className="od-tab">Pay</div>
        <div className="od-tab">Docs</div>
        <div className="od-tab od-tab-active">Board</div>
        <div className="od-tab">Msgs</div>
      </div>
    </div>
  );
}

/* ============ INPUT ============ */
function Field({ label, ...props }) {
  return (
    <label className="od-field">
      <span className="od-field-label">{label}</span>
      <input className="od-field-input" {...props} />
    </label>
  );
}

/* ============ WAITLIST FORM ============ */
function WaitlistForm({ compact = false, ltvCopy }) {
  const [role, setRole] = useState("");
  const [done, setDone] = useState(false);

  function handleSubmit(e) {
    e.preventDefault();
    const name = e.target.name.value;
    localStorage.setItem("od_waitlist", JSON.stringify({ name, email: e.target.email.value, role, at: Date.now() }));
    setDone(true);
  }

  if (done) {
    return (
      <div className="od-form-done">
        <div className="od-form-done-icon">✓</div>
        <div className="od-form-done-title">You're on the list.</div>
        <p className="od-form-done-body">We'll email you the day OneDoor opens. Early founders get a note from us within 48 hours.</p>
      </div>
    );
  }

  return (
    <form className={`od-form ${compact ? "od-form-compact" : ""}`} onSubmit={handleSubmit}>
      {ltvCopy && <div className="od-form-ltv">{ltvCopy}</div>}
      <div className="od-form-row">
        <Field label="Your name" name="name" type="text" placeholder="Alex Rivera" required />
        <Field label="Email" name="email" type="email" placeholder="alex@paradisepalms.com" required />
      </div>
      <div className="od-field">
        <span className="od-field-label">I'm a…</span>
        <div className="od-role-row">
          {[
            ["admin","Board / Admin","I help run a building"],
            ["owner","Owner / Resident","I live in one"],
            ["manager","Property Manager","I manage buildings"],
          ].map(([v,l,s])=>(
            <button type="button" key={v}
              className={`od-role ${role===v ? "od-role-active" : ""}`}
              onClick={()=>setRole(v)}>
              <div className="od-role-l">{l}</div>
              <div className="od-role-s">{s}</div>
            </button>
          ))}
        </div>
      </div>
      <button className="od-btn od-btn-gradient od-btn-lg" type="submit" disabled={!role}>
        Join the waitlist
      </button>
      <p className="od-form-fine">
        No spam. One email when we launch, and occasional progress notes. Unsubscribe anytime.
      </p>
    </form>
  );
}

/* ============ FAQ ============ */
function FAQ({ q, a, open, onClick }) {
  return (
    <div className={`od-faq ${open ? "od-faq-open" : ""}`}>
      <button className="od-faq-q" onClick={onClick}>
        <span>{q}</span>
        <span className="od-faq-chev">+</span>
      </button>
      <div className="od-faq-a"><p>{a}</p></div>
    </div>
  );
}

/* ============ EDIT MODE (Tweaks) PANEL ============ */
function TweaksPanel({ state, setState, defaults }) {
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(false);

  useEffect(() => {
    function onMsg(e) {
      if (e.data?.type === "__activate_edit_mode") { setActive(true); setOpen(true); }
      if (e.data?.type === "__deactivate_edit_mode") { setActive(false); setOpen(false); }
    }
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  function update(patch) {
    const next = { ...state, ...patch };
    setState(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: patch }, "*");
  }

  if (!active) return null;

  return (
    <div className="od-tweaks">
      <div className="od-tweaks-head" onClick={()=>setOpen(!open)}>
        <span>Tweaks</span>
        <span style={{opacity:.6, fontSize:12}}>{open ? "▾" : "▸"}</span>
      </div>
      {open && (
        <div className="od-tweaks-body">
          <div className="od-tweak">
            <div className="od-tweak-lab">Hero variation</div>
            <div className="od-tweak-segs">
              {["split","centered","showcase"].map(v => (
                <button key={v}
                  className={state.heroVariant === v ? "od-seg od-seg-on" : "od-seg"}
                  onClick={()=>update({heroVariant:v})}>{v}</button>
              ))}
            </div>
          </div>
          <div className="od-tweak">
            <div className="od-tweak-lab">Headline</div>
            <div className="od-tweak-segs od-tweak-segs-stack">
              {defaults.headlines.map((h,i) => (
                <button key={i}
                  className={state.headlineIdx === i ? "od-seg od-seg-on" : "od-seg"}
                  onClick={()=>update({headlineIdx:i})}>
                  {h.title.split("\n")[0]}
                </button>
              ))}
            </div>
          </div>
          <div className="od-tweak">
            <div className="od-tweak-lab">LTV offer wording</div>
            <div className="od-tweak-segs od-tweak-segs-stack">
              {defaults.ltvOptions.map((o,i) => (
                <button key={i}
                  className={state.ltvIdx === i ? "od-seg od-seg-on" : "od-seg"}
                  onClick={()=>update({ltvIdx:i})}>
                  {o.short}
                </button>
              ))}
            </div>
          </div>
          <div className="od-tweak">
            <div className="od-tweak-lab">Sections</div>
            {[
              ["showProblem","Problem"],
              ["showHowItWorks","How it works"],
              ["showScreens","Screenshots"],
              ["showFounder","Founder's note"],
              ["showSocial","Testimonials"],
              ["showFAQ","FAQ"],
            ].map(([k,l]) => (
              <label key={k} className="od-tweak-check">
                <input type="checkbox" checked={state[k]} onChange={e=>update({[k]:e.target.checked})}/>
                <span>{l}</span>
              </label>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  Aurora, Wordmark, Button, Pill, Section, Phone,
  HomeScreen, PaymentsScreen, BoardScreen,
  Field, WaitlistForm, FAQ, TweaksPanel,
});
