// battery-app.jsx
// The Battery — coming-soon landing page

const { useState } = React;

async function postJSON(url, data) {
  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || "Request failed");
  }
  return res.json();
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "aesthetic": "heritage",
  "palette": "warm",
  "opening": "Spring 2028",
  "grain": true,
  "wordmark": "lockup"
} /*EDITMODE-END*/;

const AESTHETIC_LABELS = {
  heritage: "Heritage",
  modern: "Modern",
  editorial: "Editorial",
  bold: "Bold"
};

const PALETTE_LABELS = {
  warm: "Warm brick",
  cool: "Cool slate",
  mono: "Monochrome",
  earth: "Earthy ochre"
};

const PALETTE_SWATCHES = {
  warm: ["#efe6d2", "#9c3a18", "#1a120a"],
  cool: ["#e6e2d8", "#1d3a55", "#131c25"],
  mono: ["#f3eee2", "#0c0a07", "#5a5048"],
  earth: ["#e7ddc2", "#8a4a28", "#25200f"]
};

const Arrow = () =>
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M3 8h10M9 4l4 4-4 4" />
  </svg>;


const Check = () =>
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M3 8.5l3.5 3.5L13 5" />
  </svg>;


function Wordmark({ style }) {
  if (style === "stacked") {
    return (
      <h1 className="wordmark wordmark-stacked">
        <span style={{ display: "block" }}>The</span>
        <span style={{ display: "block" }}>Battery</span>
      </h1>);

  }
  return <h1 className="wordmark">The Battery</h1>;
}

function PalettePicker({ value, onChange }) {
  return (
    <div className="twk-row">
      <div className="twk-lbl"><span>Color story</span><span className="twk-val">{PALETTE_LABELS[value]}</span></div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
        {Object.entries(PALETTE_SWATCHES).map(([id, colors]) => {
          const on = id === value;
          return (
            <button
              key={id}
              type="button"
              role="radio"
              aria-checked={on}
              aria-label={PALETTE_LABELS[id]}
              title={PALETTE_LABELS[id]}
              onClick={() => onChange(id)}
              style={{
                appearance: "none",
                border: on ? "1.5px solid rgba(41,38,27,0.85)" : "0.5px solid rgba(41,38,27,0.25)",
                borderRadius: 8,
                padding: 0,
                height: 40,
                cursor: "pointer",
                overflow: "hidden",
                display: "flex",
                background: colors[0],
                position: "relative",
                boxShadow: on ? "0 0 0 2px rgba(255,255,255,0.6)" : "none"
              }}>

              <span style={{ flex: 1, background: colors[0] }} />
              <span style={{ width: "32%", display: "flex", flexDirection: "column" }}>
                <span style={{ flex: 1, background: colors[1] }} />
                <span style={{ flex: 1, background: colors[2] }} />
              </span>
            </button>);

        })}
      </div>
    </div>);

}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [email, setEmail] = useState("");
  const [subscribed, setSubscribed] = useState(false);
  const [subError, setSubError] = useState("");
  const [subLoading, setSubLoading] = useState(false);
  const [interest, setInterest] = useState("residential");
  const [contact, setContact] = useState({ name: "", email: "", message: "" });
  const [sent, setSent] = useState(false);
  const [contactError, setContactError] = useState("");
  const [contactLoading, setContactLoading] = useState(false);

  const submitEmail = async (e) => {
    e.preventDefault();
    if (!email || !email.includes("@")) return;
    setSubError("");
    setSubLoading(true);
    try {
      await postJSON("/api/subscribe", { email });
      setSubscribed(true);
    } catch (err) {
      setSubError(err.message || "Something went wrong. Try again.");
    } finally {
      setSubLoading(false);
    }
  };

  const submitContact = async (e) => {
    e.preventDefault();
    if (!contact.name || !contact.email || !contact.message) return;
    setContactError("");
    setContactLoading(true);
    try {
      await postJSON("/api/contact", { ...contact, interest });
      setSent(true);
    } catch (err) {
      setContactError(err.message || "Something went wrong. Try again.");
    } finally {
      setContactLoading(false);
    }
  };

  return (
    <div
      className="page"
      data-aesthetic={t.aesthetic}
      data-palette={t.palette}
      data-grain={t.grain ? "true" : "false"}>

      {/* ============ TOPBAR ============ */}
      <header className="topbar">
        <div className="mark">
          <span className="mark-glyph" aria-hidden="true"></span>
          <span>The Battery · Waterloo</span>
        </div>
        <div className="topbar-right">
          <span className="hide-sm">221 W. 5th Street</span>
          <span className="dot hide-sm">·</span>
          <span>Waterloo, Iowa</span>
          <span className="dot">·</span>
          <span>Coming {t.opening}</span>
        </div>
      </header>

      {/* ============ HERO ============ */}
      <section className="hero">
        <div className="hero-meta">
          <span className="pulse" aria-hidden="true"></span>
          <span>Now in development</span>
          <span>·</span>
          <span>Historic adaptive reuse</span>
          <span>·</span>
          <span>EST. CIRCA 1912</span>
        </div>

        <div className="hero-grid">
          <div className="hero-text">
            <Wordmark style={t.wordmark} />
            <p className="lede">
              A historic landmark restored. Twenty mixed-income residences above a
              café, coworking suite, and public commons — in the heart of downtown
              Waterloo.
            </p>
          </div>

          <figure className="hero-figure">
            <div className="hero-photo">
              <image-slot
                id="battery-exterior"
                src="images/battery-exterior.jpg"
                placeholder="Drop a building photo or rendering here">
              </image-slot>
            </div>
            <figcaption className="photo-meta">
              <span className="num">FIG. 01</span>
              <span>·</span>
              <span>Rendering, corner view at dusk</span>
            </figcaption>
          </figure>
        </div>
      </section>

      {/* ============ NOTE ============ */}
      <section className="note-block">
        <span className="section-label" data-num="—">A note on the building</span>
        <p>
          An early-twentieth-century industrial structure, idle for decades, returns
          as a mixed-use anchor for downtown Waterloo's urban core. Preserved
          facade, restored masonry, twenty residences above — and at the street,
          three new neighbors: a café, a coworking suite, and a public commons.
        </p>
      </section>

      {/* ============ FACTS ============ */}
      <section className="facts" aria-label="Project at a glance">
        <div className="fact">
          <span className="fact-num">20</span>
          <span className="fact-label">Mixed-income residences</span>
        </div>
        <div className="fact">
          <span className="fact-num fact-trio">
            <span>Café</span>
            <span className="fact-sep">·</span>
            <span>Coworking</span>
            <span className="fact-sep">·</span>
            <span>Commons</span>
          </span>
          <span className="fact-label">2,600 sq ft at the street</span>
        </div>
        <div className="fact">
          <span className="fact-num">1</span>
          <span className="fact-label">Historic landmark, restored</span>
        </div>
      </section>

      {/* ============ EMAIL SIGNUP ============ */}
      <section className="signup">
        <div>
          <div className="section-label" data-num="01 —">Stay informed</div>
          <h2>First to know.</h2>
        </div>
        <div className="signup-form">
          <p>
            Updates on leasing, ground-floor commercial opportunities, and the
            opening calendar. No clutter — a handful of notes a year.
          </p>
          {subscribed ?
          <div className="success" style={{ marginTop: 28 }}>
              <Check />
              <span>You're on the list. We'll be in touch.</span>
            </div> :

          <form onSubmit={submitEmail} style={{ marginTop: 28 }}>
              <div className="field">
                <label className="field-label" htmlFor="email">Email address</label>
                <div className="email-row">
                  <input
                  id="email"
                  type="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  autoComplete="email" />

                  <button className="btn-arrow" type="submit" disabled={subLoading}
                    style={{ opacity: subLoading ? 0.6 : undefined }}>
                    {subLoading ? "Sending…" : <><span>Subscribe</span> <Arrow /></>}
                  </button>
                </div>
              </div>
              {subError && <p className="signup-meta" style={{ color: "var(--accent)" }}>{subError}</p>}
              <p className="signup-meta">
                We'll only email about The Battery. Unsubscribe anytime.
              </p>
            </form>
          }
        </div>
      </section>

      {/* ============ CONTACT ============ */}
      <section className="contact">
        <div>
          <div className="section-label" data-num="02 —">Inquiries</div>
          <h2>Get in touch.</h2>
          <p>
            For residential pre-leasing, ground-floor commercial opportunities,
            press, or partnership questions — write us directly.
          </p>
        </div>

        {sent ?
        <div style={{ alignSelf: "end" }}>
            <div className="success">
              <Check />
              <span>Message received. We'll reply within a few days.</span>
            </div>
            <p className="signup-meta" style={{ marginTop: 20 }}>
              Or email us directly at <span style={{ color: "var(--ink)" }}>contact@astracommons.com</span>
            </p>
          </div> :

        <form className="contact-form" onSubmit={submitContact}>
            <div className="field full">
              <label className="field-label">I'm interested in</label>
              <div className="interest-pills" role="radiogroup">
                {[
              { id: "residential", label: "Residential leasing" },
              { id: "commercial", label: "Commercial / retail" },
              { id: "press", label: "Press" },
              { id: "other", label: "Something else" }].
              map((opt) =>
              <button
                key={opt.id}
                type="button"
                role="radio"
                aria-checked={interest === opt.id}
                className={`pill ${interest === opt.id ? "active" : ""}`}
                onClick={() => setInterest(opt.id)}>

                    {opt.label}
                  </button>
              )}
              </div>
            </div>

            <div className="field">
              <label className="field-label" htmlFor="c-name">Name</label>
              <input
              id="c-name"
              value={contact.name}
              onChange={(e) => setContact({ ...contact, name: e.target.value })}
              placeholder="Full name" />

            </div>

            <div className="field">
              <label className="field-label" htmlFor="c-email">Email</label>
              <input
              id="c-email"
              type="email"
              value={contact.email}
              onChange={(e) => setContact({ ...contact, email: e.target.value })}
              placeholder="you@example.com" />

            </div>

            <div className="field full">
              <label className="field-label" htmlFor="c-msg">Message</label>
              <textarea
              id="c-msg"
              value={contact.message}
              onChange={(e) => setContact({ ...contact, message: e.target.value })}
              placeholder="Tell us a little about what you're looking for." />

            </div>

            {contactError && (
              <div className="full" style={{ color: "var(--accent)", fontSize: 13 }}>{contactError}</div>
            )}
            <div className="submit-row">
              <span className="submit-note">We typically reply within 2 business days.</span>
              <button className="btn-arrow" type="submit" disabled={contactLoading}
                style={{ opacity: contactLoading ? 0.6 : undefined }}>
                {contactLoading ? "Sending…" : <><span>Send inquiry</span> <Arrow /></>}
              </button>
            </div>
          </form>
        }
      </section>

      {/* ============ FOOTER ============ */}
      <footer className="footer">
        <div>
          <div className="footer-mark">The Battery</div>
          <div>A historic adaptive reuse · Waterloo, Iowa</div>
        </div>
        <div>
          <span className="col-title">Visit</span>
          <ul>
            <li>221 W. 5th Street</li>
            <li>Waterloo, IA 50701</li>
          </ul>
        </div>
        <div>
          <span className="col-title">Contact</span>
          <ul>
            <li><a href="mailto:contact@astracommons.com">contact@astracommons.com</a></li>
          </ul>
        </div>
        <div>
          <span className="col-title">Project</span>
          <ul>
            <li>20 residences</li>
            <li>Café · Coworking · Commons</li>
            <li>Opening {t.opening}</li>
          </ul>
        </div>
        <div className="footer-bottom">
          <span>© 2026 The Battery Waterloo. All rights reserved.</span>
          <span>thebatterywaterloo.com</span>
        </div>
      </footer>

      {/* ============ TWEAKS ============ */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Aesthetic" />
        <TweakSelect
          label="Direction"
          value={t.aesthetic}
          options={Object.entries(AESTHETIC_LABELS).map(([value, label]) => ({ value, label }))}
          onChange={(v) => setTweak("aesthetic", v)} />

        <TweakRadio
          label="Wordmark"
          value={t.wordmark}
          options={[
          { value: "lockup", label: "Inline" },
          { value: "stacked", label: "Stacked" }]
          }
          onChange={(v) => setTweak("wordmark", v)} />


        <TweakSection label="Palette" />
        <PalettePicker
          value={t.palette}
          onChange={(v) => setTweak("palette", v)} />


        <TweakSection label="Texture" />
        <TweakToggle
          label="Paper grain"
          value={t.grain}
          onChange={(v) => setTweak("grain", v)} />


        <TweakSection label="Content" />
        <TweakText
          label="Opening date"
          value={t.opening}
          onChange={(v) => setTweak("opening", v)} />

      </TweaksPanel>
    </div>);

}

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