/* global React, supabase */
const { useState: useStateC } = React;

const _LEAD_SB_URL = 'https://bhbksroyflcnqvauttvg.supabase.co';
const _LEAD_SB_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJoYmtzcm95ZmxjbnF2YXV0dHZnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzc4OTc1MTMsImV4cCI6MjA5MzQ3MzUxM30.Zb0zSuNcDtu5XlYsUevxz4PXVZGsL-bAE9wXwrkLR0k';

function ServiceAreaMap() {
  // Simplified South Florida coast silhouette
  // Pins positioned by approximate percentage coordinates
  const pins = [
    { top: "16%", left: "78%", label: "West Palm Beach" },
    { top: "28%", left: "72%", label: "Boca Raton" },
    { top: "36%", left: "70%", label: "Fort Lauderdale" },
    { top: "48%", left: "70%", label: "Hollywood" },
    { top: "58%", left: "68%", label: "Miami Beach" },
    { top: "66%", left: "60%", label: "Coral Gables" },
    { top: "72%", left: "56%", label: "Pinecrest" },
  ];

  return (
    <section id="area" className="section map-section" data-screen-label="Service Area">
      <div className="section-header">
        <div>
          <div className="index">07 · Service Area</div>
          <h2>Miami, Fort Lauderdale, <span className="italic-accent">and beyond.</span></h2>
        </div>
        <div className="header-right">
          <p className="lede" style={{ margin: 0 }}>
            {window.COPY.serviceAreaLede}
          </p>
        </div>
      </div>

      <div className="map-wrap">
        <div className="map-copy">
          <div className="eyebrow"><span className="dot"/>Core markets</div>
          <h3>Grounded in South Florida.</h3>
          <p>Most of our work concentrates in a handful of high-demand neighborhoods we know block by block.</p>
          <ul>
            <li>Miami Beach <span>Miami-Dade</span></li>
            <li>Coral Gables <span>Miami-Dade</span></li>
            <li>Pinecrest <span>Miami-Dade</span></li>
            <li>Bay Harbor Islands <span>Miami-Dade</span></li>
            <li>Fort Lauderdale <span>Broward</span></li>
            <li>Hollywood <span>Broward</span></li>
            <li>Boca Raton <span>Palm Beach</span></li>
          </ul>
        </div>

        <div className="map-figure">
          <svg viewBox="0 0 400 300" preserveAspectRatio="none" aria-hidden="true">
            {/* Water */}
            <rect width="400" height="300" fill="#EFD09F" />
            {/* Coastline / land mass — simplified SE Florida */}
            <path
              d="M 0 0 L 260 0 L 265 20 L 268 40 L 270 60 L 272 85 L 275 105 L 280 125 L 278 150 L 275 175 L 270 200 L 260 225 L 245 250 L 225 275 L 200 290 L 170 300 L 0 300 Z"
              fill="#F8EDD5"
              stroke="#653211"
              strokeWidth="0.8"
              strokeOpacity="0.3"
            />
            {/* Inland rule marks */}
            <g stroke="#653211" strokeOpacity="0.08" strokeWidth="0.5">
              <line x1="0" y1="80" x2="260" y2="80" />
              <line x1="0" y1="160" x2="270" y2="160" />
              <line x1="0" y1="240" x2="240" y2="240" />
              <line x1="100" y1="0" x2="100" y2="300" />
              <line x1="180" y1="0" x2="180" y2="300" />
            </g>
            {/* Highway lines */}
            <path d="M 120 0 L 135 300" stroke="#653211" strokeOpacity="0.2" strokeWidth="0.6" strokeDasharray="2 3"/>
            {/* Label marks */}
            <text x="40" y="30" fill="#653211" fillOpacity="0.4" fontSize="7" fontFamily="Space Grotesk" letterSpacing="1">FLORIDA</text>
            <text x="300" y="150" fill="#653211" fillOpacity="0.4" fontSize="7" fontFamily="Space Grotesk" letterSpacing="1">ATLANTIC</text>
          </svg>
          {pins.map(p => (
            <div key={p.label} className="pin" style={{ top: p.top, left: p.left }}>
              <span className="pin-dot" />
              <span className="pin-label">{p.label}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ContactSection() {
  const [audience, setAudience] = useStateC("homeowner");
  const [form, setForm] = useStateC({
    name: "", email: "", phone: "",
    projectType: "", message: "",
  });
  const [status, setStatus] = useStateC("idle"); // idle | sending | sent | error

  const copy = audience === "investor"
    ? {
        eyebrow: "Investor inquiries",
        headline: (<>Let's find the <em>next opportunity.</em></>),
        sub: window.COPY.contactInvestorSub,
        cta: "Send to investor team",
      }
    : {
        eyebrow: "Homeowner inquiries",
        headline: (<>Tell us about <em>your home.</em></>),
        sub: window.COPY.contactHomeownerSub,
        cta: "Send to build team",
      };

  const submit = async (e) => {
    e.preventDefault();
    setStatus("sending");
    try {
      const sb = supabase.createClient(_LEAD_SB_URL, _LEAD_SB_KEY);
      const { error } = await sb.from('onehaus_leads').insert({
        audience,
        name: form.name,
        email: form.email,
        phone: form.phone || null,
        project_type: form.projectType || null,
        message: form.message || null,
      });
      if (error) throw error;
      setStatus("sent");
      setForm({ name: "", email: "", phone: "", projectType: "", message: "" });
      setTimeout(() => setStatus("idle"), 4000);
    } catch(err) {
      setStatus("error");
      setTimeout(() => setStatus("idle"), 4000);
    }
  };

  return (
    <>
      <section id="contact" className="contact" data-screen-label="Contact">
        <div className="contact-inner">
          <div className="contact-intro">
            <div className="eyebrow"><span className="dot" style={{ background: "var(--beige)" }}/>08 · Contact</div>
            <h2>Start a conversation <em>— in Haus.</em></h2>
            <p>{window.COPY.contactBody}</p>
            <div className="contact-details">
              <div className="row"><span className="lbl">Phone</span><span className="val">{window.CONTACT.phone}</span></div>
              <div className="row"><span className="lbl">Email</span><span className="val">{window.CONTACT.email}</span></div>
              <div className="row"><span className="lbl">Area</span><span className="val">{window.CONTACT.area}</span></div>
              <div className="row"><span className="lbl">Hours</span><span className="val">{window.CONTACT.hours}</span></div>
            </div>
          </div>

          <form className="contact-form" onSubmit={submit}>
            <div className="eyebrow"><span className="dot"/>{copy.eyebrow}</div>
            <h3>{copy.headline}</h3>
            <p style={{ color: "var(--ink-mute)", margin: "0 0 24px", fontSize: 14, lineHeight: 1.55 }}>
              {copy.sub}
            </p>

            <div className="audience-toggle" role="tablist" aria-label="Audience">
              <button type="button" className={audience === "homeowner" ? "is-active" : ""} onClick={() => setAudience("homeowner")}>Homeowner</button>
              <button type="button" className={audience === "investor" ? "is-active" : ""} onClick={() => setAudience("investor")}>Investor</button>
            </div>

            <div className="field-grid">
              <div className="field">
                <label htmlFor="f-name">Name</label>
                <input id="f-name" required value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="Your full name"/>
              </div>
              <div className="field">
                <label htmlFor="f-email">Email</label>
                <input id="f-email" type="email" required value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="you@domain.com"/>
              </div>
              <div className="field">
                <label htmlFor="f-phone">Phone</label>
                <input id="f-phone" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} placeholder="(305) 000 — 0000"/>
              </div>
              <div className="field">
                <label htmlFor="f-type">Project type</label>
                <select id="f-type" value={form.projectType} onChange={e => setForm({...form, projectType: e.target.value})}>
                  <option value="">Select…</option>
                  <option>New Build</option>
                  <option>Renovation</option>
                  <option>Investment</option>
                  <option>Other</option>
                </select>
              </div>
              <div className="field col-2">
                <label htmlFor="f-msg">Message</label>
                <textarea id="f-msg" value={form.message} onChange={e => setForm({...form, message: e.target.value})} placeholder="A few lines on scope, location, timeline…" rows="3"/>
              </div>
            </div>

            <div className="form-actions">
              <div className="fine">
                By submitting, you agree to be contacted by One Haus Developments. We never share your information.
              </div>
              <button type="submit" className="btn btn-primary" disabled={status === "sending"}>
                {status === "sending" ? "Sending…"
                  : status === "sent" ? "Thank you — we'll be in touch"
                  : status === "error" ? "Something went wrong — please try again"
                  : copy.cta} <span className="arrow"/>
              </button>
            </div>
          </form>
        </div>
      </section>

      <footer className="footer">
        <div className="footer-inner">
          <div className="wordmark">
            <img src="images/logo/beige.png" alt="One Haus Developments" className="nav-logo" />
          </div>
          <div>{window.COPY.footerCopyright}</div>
          <div style={{ display: "flex", gap: 18 }}>
            <a href={window.COPY.instagramUrl} target="_blank" rel="noopener">Instagram</a>
            <a href="#">Privacy</a>
            <a href="admin.html" target="_blank" rel="noopener" style={{ opacity: 0.45, fontSize: 11 }}>Admin</a>
          </div>
        </div>
      </footer>
    </>
  );
}

Object.assign(window, { ServiceAreaMap, ContactSection });
