const { Button, IconBadge, HeartDivider, Badge, Card, FeatureItem, Stat, Input } = window.TwinCitiesLivingAssistanceDesignSystem_f22824;
const { PHONE, PHONE2, EMAIL, ADDRESS, scrollToId, Container, Section, Eyebrow, SectionHead } = window;

/* ---------------- Header ---------------- */
function Header() {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", on); on();
    return () => window.removeEventListener("scroll", on);
  }, []);
  const links = [["services", "Services"], ["home-tour", "The Home"], ["pricing", "Pricing"], ["faq", "FAQ"], ["contact", "Contact"]];
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 50, background: "rgba(247,245,239,0.94)", backdropFilter: "blur(8px)", borderBottom: `1px solid ${scrolled ? "var(--line-200)" : "transparent"}`, boxShadow: scrolled ? "var(--shadow-sm)" : "none", transition: "box-shadow var(--dur-base), border-color var(--dur-base)" }}>
      <Container width="var(--container-xl)" style={{ display: "flex", alignItems: "center", gap: 20, padding: "10px 28px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, cursor: "pointer" }} onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>
          <img src="assets/logo-mark.png" alt="Twin Cities Living Assistance" style={{ height: 46 }} />
          <div style={{ lineHeight: 1.05 }}>
            <div style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontWeight: 600, fontSize: "1.3rem", color: "var(--navy-700)" }}>Twin Cities</div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "0.6rem", letterSpacing: "0.18em", color: "var(--green-800)" }}>LIVING ASSISTANCE</div>
          </div>
        </div>
        <nav style={{ display: "flex", gap: 26, marginLeft: "auto", alignItems: "center" }} className="tcla-nav">
          {links.map(([k, label]) => (
            <span key={k} onClick={() => scrollToId(k)} style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "0.9rem", letterSpacing: "0.02em", textTransform: "uppercase", cursor: "pointer", color: "var(--navy-700)" }} className="tcla-navlink">{label}</span>
          ))}
        </nav>
        <a href={`tel:${PHONE.replace(/-/g, "")}`} className="tcla-phone" style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "0.95rem", color: "var(--navy-700)", textDecoration: "none", display: "flex", alignItems: "center", gap: 8 }}>
          <i className="fa-solid fa-phone" style={{ color: "var(--green-600)" }} aria-hidden="true"></i>{PHONE}
        </a>
        <Button size="sm" icon="fa-solid fa-calendar-check" onClick={() => scrollToId("tour")}>Schedule a Tour</Button>
      </Container>
    </header>
  );
}

/* ---------------- Tour form ---------------- */
function TourForm() {
  const [f, setF] = React.useState({ name: "", phone: "", email: "", date: "", relation: "", message: "" });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const validate = () => {
    const er = {};
    if (!f.name.trim()) er.name = "Please enter your name";
    if (!/^[\d\s()+-]{7,}$/.test(f.phone.trim())) er.phone = "Enter a valid phone number";
    if (!/^\S+@\S+\.\S+$/.test(f.email.trim())) er.email = "Enter a valid email";
    setErrors(er);
    return Object.keys(er).length === 0;
  };
  const submit = async (e) => {
    e.preventDefault();
    if (!validate() || submitting) return;

    setSubmitting(true);
    try {
      // Capture UTM params from URL
      const _p = new URLSearchParams(window.location.search);
      const _utmSource   = _p.get('utm_source')   || '';
      const _utmMedium   = _p.get('utm_medium')   || '';
      const _utmCampaign = _p.get('utm_campaign') || '';
      const _utmContent  = _p.get('utm_content')  || '';
      const _fbclid      = _p.get('fbclid')       || '';
      const _gclid       = _p.get('gclid')        || '';
      const _pageUrl     = window.location.href;

      const _tags = ['lp-lead', 'tour-request'];
      if (_utmSource)   _tags.push('src-'  + _utmSource);
      if (_utmMedium)   _tags.push('med-'  + _utmMedium);
      if (_utmCampaign) _tags.push('camp-' + _utmCampaign);

      const contactRes = await fetch("https://services.leadconnectorhq.com/contacts/", {
        method: "POST",
        headers: {
          Authorization: "Bearer pit-3e5008ff-7afb-49e3-9d0e-fa672d6a296b",
          "Content-Type": "application/json",
          "Version": "2021-07-28",
        },
        body: JSON.stringify({
          firstName: f.name.trim(),
          phone: f.phone.trim(),
          email: f.email.trim(),
          locationId: "ztfUkl82Imwh5KNdRcCa",
          source: _utmSource ? 'LP - ' + _utmSource : 'Twin Cities LP',
          tags: _tags,
          customFields: [
            { key: "relation", value: f.relation.trim() },
            { key: "preferred_date", value: f.date },
            { key: "message", value: f.message.trim() },
          ].filter(x => x.value),
        }),
      });

      if (!contactRes.ok) {
        throw new Error(`Contact create failed: ${contactRes.status} ${await contactRes.text()}`);
      }

      const contactData = await contactRes.json();
      const contactId = contactData?.contact?.id || contactData?.id;

      if (!contactId) {
        throw new Error("Contact create succeeded but no contact id was returned");
      }

      // Post UTM note to contact
      if (_utmSource || _utmMedium || _utmCampaign || _fbclid || _gclid || f.relation || f.message) {
        const _noteLines = [];
        if (_utmSource)   _noteLines.push('UTM Source: '   + _utmSource);
        if (_utmMedium)   _noteLines.push('UTM Medium: '   + _utmMedium);
        if (_utmCampaign) _noteLines.push('UTM Campaign: ' + _utmCampaign);
        if (_utmContent)  _noteLines.push('UTM Content: '  + _utmContent);
        if (_fbclid)      _noteLines.push('FB Click ID: '  + _fbclid);
        if (_gclid)       _noteLines.push('Google Click ID: ' + _gclid);
        if (_pageUrl)     _noteLines.push('Landing Page: ' + _pageUrl);
        if (f.relation)   _noteLines.push('Relation to loved one: ' + f.relation.trim());
        if (f.message)    _noteLines.push('Message: ' + f.message.trim());
        fetch("https://services.leadconnectorhq.com/contacts/" + contactId + "/notes", {
          method: "POST",
          headers: { Authorization: "***", "Content-Type": "application/json", "Version": "2021-07-28" },
          body: JSON.stringify({ body: _noteLines.join("\n"), userId: "" }),
        }).catch(() => {});
      }

      const oppRes = await fetch("https://services.leadconnectorhq.com/opportunities/", {
        method: "POST",
        headers: {
          Authorization: "Bearer pit-3e5008ff-7afb-49e3-9d0e-fa672d6a296b",
          "Content-Type": "application/json",
          "Version": "2021-07-28",
        },
        body: JSON.stringify({
          pipelineId: "s52wfEibBGSJQuW4a9NG",
          pipelineStageId: "2659ac5f-4a56-41f4-8f28-0963c8cd1864",
          locationId: "ztfUkl82Imwh5KNdRcCa",
          contactId,
          name: `Tour Request - ${f.name.trim()}`,
          status: "open",
          source: "Twin Cities LP",
        }),
      });

      if (!oppRes.ok) {
        throw new Error(`Opportunity create failed: ${oppRes.status} ${await oppRes.text()}`);
      }
      // Fire Meta Pixel Lead event on successful submission
      if (typeof fbq === 'function') {
        fbq('track', 'Lead', { content_name: 'Tour Request', content_category: 'Assisted Living' });
      }
    } catch (err) {
      console.error("Twin Cities LP form submission failed:", err);
    } finally {
      window.location.href = 'https://go.twincitieslivingassistance.com/thank-you';
      setSubmitting(false);
      setSent(true);
    }
  };

  if (sent) return (
    <div style={cardShell}>
      <div style={{ textAlign: "center", padding: "18px 6px" }}>
        <IconBadge icon="fa-solid fa-check" color="green" size="lg" style={{ margin: "0 auto 18px" }} />
        <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "1.6rem", color: "var(--navy-700)", margin: "0 0 10px" }}>Thank you, {f.name.split(" ")[0]}!</h3>
        <p style={{ fontFamily: "var(--font-body)", fontSize: "1rem", lineHeight: 1.6, color: "var(--ink-600)", margin: "0 0 22px" }}>We've received your request and will call you at <strong style={{ color: "var(--navy-700)" }}>{f.phone}</strong> within one business day to confirm your visit.</p>
        <Button variant="outline" icon="fa-solid fa-phone" href={`tel:${PHONE.replace(/-/g, "")}`}>Or call us now: {PHONE}</Button>
      </div>
    </div>
  );

  return (
    <form style={cardShell} onSubmit={submit} noValidate>
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "1.45rem", color: "var(--navy-700)", lineHeight: 1.15 }}>Schedule a private tour</div>
        <div style={{ fontFamily: "var(--font-body)", fontSize: "0.95rem", color: "var(--ink-600)", marginTop: 6 }}>No obligation. We'll follow up within one business day.</div>
      </div>
      <div style={{ display: "grid", gap: 14 }}>
        <Field error={errors.name}><Input label="Your name" icon="fa-solid fa-user" placeholder="Jane Smith" value={f.name} onChange={set("name")} /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="tcla-form2">
          <Field error={errors.phone}><Input label="Phone" icon="fa-solid fa-phone" placeholder="612-555-0100" value={f.phone} onChange={set("phone")} /></Field>
          <Field error={errors.email}><Input label="Email" icon="fa-solid fa-envelope" placeholder="you@email.com" value={f.email} onChange={set("email")} /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="tcla-form2">
          <Input label="Preferred date" icon="fa-solid fa-calendar" type="date" value={f.date} onChange={set("date")} />
          <div>
            <label style={{ display: "block", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--text-heading)", marginBottom: 6 }}>Caring for</label>
            <div style={{ display: "flex", alignItems: "center", gap: 10, background: "#fff", border: "1.5px solid var(--border-strong)", borderRadius: "var(--radius-md)", padding: "0 14px" }}>
              <i className="fa-solid fa-people-roof" style={{ color: "var(--ink-400)", fontSize: "0.95rem" }} aria-hidden="true"></i>
              <select value={f.relation} onChange={set("relation")} style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-body)", fontSize: "var(--fs-body)", color: "var(--ink-900)", padding: "13px 0" }}>
                <option value="">Select…</option>
                <option>A parent</option><option>My spouse</option><option>Myself</option><option>Another relative</option>
              </select>
            </div>
          </div>
        </div>
        <Input label="Anything we should know? (optional)" multiline rows={2} placeholder="Care needs, timing, questions…" value={f.message} onChange={set("message")} />
        <Button type="submit" size="lg" fullWidth icon="fa-solid fa-calendar-check" style={{ marginTop: 4 }} disabled={submitting}>{submitting ? "Sending..." : "Request My Tour"}</Button>
        <div style={{ fontFamily: "var(--font-body)", fontSize: "0.8rem", color: "var(--ink-400)", textAlign: "center" }}>Or call <a href={`tel:${PHONE.replace(/-/g, "")}`} style={{ color: "var(--green-800)", fontWeight: 600 }}>{PHONE}</a> — we're here 24/7.</div>
      </div>
    </form>
  );
}
const cardShell = { background: "#fff", borderRadius: "var(--radius-xl)", boxShadow: "0 24px 60px rgba(8,28,64,.28)", border: "1px solid var(--line-200)", padding: "30px 30px 26px", width: "100%" };
function Field({ error, children }) {
  return <div>{children}{error && <div style={{ fontFamily: "var(--font-body)", fontSize: "0.78rem", color: "var(--red-500)", marginTop: 5, display: "flex", alignItems: "center", gap: 5 }}><i className="fa-solid fa-circle-exclamation" aria-hidden="true"></i>{error}</div>}</div>;
}

/* ---------------- Hero ---------------- */
function Hero() {
  return (
    <section id="tour" style={{ position: "relative", overflow: "hidden", background: "var(--navy-800)" }}>
      <img src="assets/care-livingroom.jpg" alt="A caregiver visiting with a resident at home" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "60% 40%" }} />
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(100deg, rgba(8,28,64,.94) 0%, rgba(8,28,64,.86) 38%, rgba(8,28,64,.55) 66%, rgba(8,28,64,.35) 100%)" }} />
      <Container width="var(--container-xl)" style={{ position: "relative", display: "grid", gridTemplateColumns: "1.05fr 0.95fr", gap: 54, alignItems: "center", padding: "76px 28px 84px" }}>
        <div className="tcla-hero-copy" style={{ color: "#fff" }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 9, background: "rgba(255,255,255,.12)", border: "1px solid rgba(255,255,255,.2)", borderRadius: "var(--radius-pill)", padding: "7px 15px", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "0.78rem", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 26 }}>
            <i className="fa-solid fa-location-dot" style={{ color: "var(--sky-300)" }} aria-hidden="true"></i> Licensed 55+ Assisted Living · Burnsville, MN
          </div>
          <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "clamp(2.4rem, 4.4vw, 3.6rem)", lineHeight: 1.04, letterSpacing: "-0.015em", margin: "0 0 22px" }}>Compassionate care in a place they can truly call home.</h1>
          <p style={{ fontFamily: "var(--font-body)", fontSize: "clamp(1.05rem, 1.5vw, 1.25rem)", lineHeight: 1.6, color: "#dbe3f0", margin: "0 0 30px", maxWidth: 540, textWrap: "pretty" }}>A small, homelike alternative to large facilities — with 24-hour awake staff, personalized care plans, and home-cooked meals. Schedule a private tour and see the difference.</p>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginBottom: 34 }}>
            <Button size="lg" icon="fa-solid fa-calendar-check" onClick={() => scrollToId("tour-form-anchor")}>Schedule a Tour</Button>
            <Button size="lg" variant="ghost" icon="fa-solid fa-phone" href={`tel:${PHONE.replace(/-/g, "")}`} style={{ color: "#fff", border: "1.5px solid rgba(255,255,255,.35)" }}>{PHONE}</Button>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: "14px 26px" }}>
            {[["fa-solid fa-clock", "24-Hour Awake Staff"], ["fa-solid fa-user-nurse", "Professional Nursing"], ["fa-solid fa-hand-holding-heart", "CADI · EW · BI Waivers"]].map(([i, t]) => (
              <div key={t} style={{ display: "flex", alignItems: "center", gap: 9, fontFamily: "var(--font-body)", fontSize: "0.95rem", color: "#eaf0fb" }}>
                <i className={i} style={{ color: "var(--green-400)" }} aria-hidden="true"></i>{t}
              </div>
            ))}
          </div>
        </div>
        <div id="tour-form-anchor"><TourForm /></div>
      </Container>
    </section>
  );
}

/* ---------------- Services ---------------- */
function Services() {
  const items = [
    ["fa-solid fa-clock", "green", "24-Hour Awake Staff", "Support and supervision available day and night — someone is always here."],
    ["fa-solid fa-pills", "green", "Medication Management", "Prescriptions organized, administered, and tracked by trained staff."],
    ["fa-solid fa-user-nurse", "green", "Professional Nursing", "Skilled nursing services and coordination with your healthcare providers."],
    ["fa-solid fa-bath", "purple", "Daily Living Assistance", "Help with bathing, dressing, grooming and mobility — with dignity."],
    ["fa-solid fa-utensils", "green", "Home-Cooked Meals", "Nutritious meals and snacks prepared fresh daily. No grocery bills."],
    ["fa-solid fa-broom", "purple", "Housekeeping & Laundry", "A clean, comfortable home — laundry and tidying handled for you."],
    ["fa-solid fa-van-shuttle", "green", "Transportation", "Rides to appointments, errands and outings, arranged as needed."],
    ["fa-solid fa-people-group", "purple", "Companionship & Activities", "Engaging activities, wellness programs and genuine companionship."],
  ];
  return (
    <Section id="services" bg="var(--cream-50)">
      <Container>
        <SectionHead eyebrow="Our Assisted Living Services" title="Everything your loved one needs, under one roof" sub="Care is customized to each resident. From help with everyday tasks to skilled nursing, our team handles it — so families can focus on time together." />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(270px, 1fr))", gap: 22, marginTop: 48 }}>
          {items.map(([icon, color, title, desc]) => (
            <Card key={title} interactive style={{ padding: "28px 26px" }}>
              <FeatureItem icon={icon} color={color} title={title} description={desc} badgeSize="lg" />
            </Card>
          ))}
        </div>
      </Container>
    </Section>
  );
}

/* ---------------- Why choose us ---------------- */
function WhyUs() {
  const stats = [
    ["24/7", "Awake staff on site", "gold"],
    ["55+", "Licensed care home", "white"],
    ["5", "Residents, not hundreds", "gold"],
    ["$300–500", "Monthly rent", "white"],
  ];
  const points = [
    ["fa-solid fa-house-chimney-window", "An intimate home, not an institution", "A small residential setting where staff know every resident by name."],
    ["fa-solid fa-clipboard-list", "Personalized care plans", "Care is tailored to each person's needs and adjusted as they change."],
    ["fa-solid fa-hand-holding-medical", "Coordinated with your providers", "We work directly with doctors and specialists on your loved one's behalf."],
    ["fa-solid fa-heart", "Genuine, compassionate people", "Warm, patient caregivers who treat residents like family."],
  ];
  return (
    <Section id="why" bg="var(--navy-700)">
      <Container>
        <SectionHead onDark eyebrow="Why families choose us" title="Care you can trust, in a home you'll love" sub="Twin Cities Living Assistance offers the personal attention of a small home with the professional care of a licensed facility." />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20, margin: "48px 0 52px" }} className="tcla-stats">
          {stats.map(([v, l, a]) => (
            <div key={l} style={{ textAlign: "center", background: "rgba(255,255,255,.06)", border: "1px solid rgba(255,255,255,.12)", borderRadius: "var(--radius-lg)", padding: "26px 16px" }}>
              <Stat value={v} label={l} onDark accent={a} align="center" />
            </div>
          ))}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 26, justifyItems: "center" }}>
          {points.map(([icon, title, desc]) => (
            <FeatureItem key={title} icon={icon} color="green" title={title} description={desc} onDark badgeSize="lg" style={{ maxWidth: 400 }} />
          ))}
        </div>
      </Container>
    </Section>
  );
}

Object.assign(window, { Header, Hero, TourForm, Services, WhyUs });
