// Section components for Premura landing page

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav${scrolled ? ' scrolled' : ''}`}>
      <div className="container nav-inner">
        <a href="#" className="nav-brand">
          <svg className="mark" viewBox="0 0 200 200" aria-hidden="true">
            <g transform="translate(70, 100)">
              <circle cx="0" cy="0" r="10" fill="#E07A66"></circle>
              <path d="M 24 -24 Q 40 0 24 24" fill="none" stroke="currentColor" strokeWidth="6" strokeLinecap="round"/>
              <path d="M 46 -46 Q 70 0 46 46" fill="none" stroke="currentColor" strokeWidth="6" strokeLinecap="round" opacity="0.7"/>
              <path d="M 68 -68 Q 100 0 68 68" fill="none" stroke="currentColor" strokeWidth="6" strokeLinecap="round" opacity="0.4"/>
            </g>
          </svg>
          <span className="word">premura</span>
        </a>
        <div className="nav-links">
          <a href="#problem">Missed calls</a>
          <a href="#customize">Tuned to you</a>
          <a href="#how">On every call</a>
        </div>
        <a href="#waitlist" className="nav-cta">Request access</a>
      </div>
    </nav>
  );
}

function Waitlist({ dark }) {
  const [email, setEmail] = React.useState("");
  const [company, setCompany] = React.useState(""); // honeypot
  const [status, setStatus] = React.useState("idle"); // idle | submitting | done | error
  const [errorMsg, setErrorMsg] = React.useState("");

  const submit = async (e) => {
    e.preventDefault();
    if (!email || status === "submitting") return;
    setStatus("submitting");
    setErrorMsg("");
    try {
      const res = await fetch("/api/waitlist", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ email, company }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setErrorMsg(data.error === "invalid_email"
          ? "Please enter a valid email address."
          : "Something went wrong. Please try again or email hello@premura.ai.");
        setStatus("error");
        return;
      }
      setStatus("done");
    } catch {
      setErrorMsg("Network error. Please try again or email hello@premura.ai.");
      setStatus("error");
    }
  };

  if (status === "done") {
    return (
      <div style={{
        display:'inline-flex', alignItems:'center', gap:10,
        padding:'14px 18px',
        background: dark ? 'rgba(255,255,255,.08)' : 'var(--success-subtle)',
        border:`1px solid ${dark ? 'rgba(255,255,255,.18)' : 'var(--success-border)'}`,
        color: dark ? '#F7F2E8' : '#1B6E66',
        borderRadius:10, fontSize:14, fontWeight:500
      }}>
        <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M4 10.5 8 14l8-9"/>
        </svg>
        You're on the list. We'll be in touch.
      </div>
    );
  }
  const submitting = status === "submitting";
  return (
    <div>
      <form className={`waitlist${dark ? ' dark' : ''}`} onSubmit={submit} noValidate>
        <input
          type="email"
          placeholder="you@your-practice.com"
          value={email}
          onChange={e => setEmail(e.target.value)}
          disabled={submitting}
          required
        />
        {/* Honeypot: hidden from humans, bots fill it. */}
        <input
          type="text"
          name="company"
          tabIndex={-1}
          autoComplete="off"
          value={company}
          onChange={e => setCompany(e.target.value)}
          style={{ position:'absolute', left:'-9999px', width:1, height:1, opacity:0 }}
          aria-hidden="true"
        />
        <button type="submit" className="btn-primary" disabled={submitting}>
          {submitting ? "Sending…" : "Request access"}
          {!submitting && (
            <svg width="14" height="14" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 10h10M11 6l4 4-4 4"/>
            </svg>
          )}
        </button>
      </form>
      {status === "error" && (
        <div role="alert" style={{
          marginTop:8, fontSize:13,
          color: dark ? '#F4B7AB' : '#B14A2F'
        }}>
          {errorMsg}
        </div>
      )}
    </div>
  );
}

function Hero({ variant }) {
  const Visual = variant === "log" ? HeroCallsLog
              : variant === "orbit" ? HeroOrbit
              : HeroTranscript;
  return (
    <section className="hero">
      <div className="container hero-grid">
        <div>
          <div className="eyebrow-row">
            <span className="dot"></span>
            <span>Now onboarding design partners</span>
            <span className="sep"></span>
            <span className="baa">HIPAA · BAA ready</span>
          </div>

          <h1 className="hero-title">
            The front desk that <span className="serif">never</span> misses a call.
          </h1>

          <p className="hero-sub">
            Premura is an AI receptionist tuned to your practice — your voice, your
            scheduling rules, your scripts, trained on your own recorded calls.
            It answers every call, books appointments straight into your schedule,
            and hands off the ones that need a human.
          </p>

          <div id="waitlist">
            <Waitlist />
          </div>

          <div className="waitlist-meta">
            <span className="check">
              <svg width="13" height="13" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M4 10.5 8 14l8-9"/>
              </svg>
              No call volume commitment
            </span>
            <span className="check">
              <svg width="13" height="13" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M4 10.5 8 14l8-9"/>
              </svg>
              BAA signed before go-live
            </span>
          </div>
        </div>

        <div>
          <Visual />
        </div>
      </div>
    </section>
  );
}

const PROBLEMS = [
  {
    stat: "1 in 3", unit: "",
    title: "calls go unanswered",
    body: "Front desks juggle check-ins, insurance forms, and the phone. New-patient calls are the first to fall through.",
    cite: "TrueLark — analysis of 8M patient conversations",
  },
  {
    stat: "47", unit: "%",
    title: "of appointment requests come in after hours",
    body: "Patients call when their tooth hurts, not when you're open. Without an answer most hang up and try the next office on the list.",
    cite: "Peerlogic / Dental Economics, 2024",
  },
  {
    stat: "$6,500", unit: "",
    title: "average lifetime revenue per patient",
    body: "Derived from ADA Health Policy Institute per-patient annual spend (~$650) over a typical 10-year relationship. A single missed new-patient call is rarely just one cleaning.",
    cite: "ADA Health Policy Institute, 2024",
  },
];

function Problem() {
  return (
    <section className="section alt" id="problem">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">The problem</span>
          <h2>Every missed call is a patient choosing <span className="serif">someone else.</span></h2>
          <p className="lede">
            Dental practices lose more revenue to unanswered phones than to no-shows.
            The fix isn't another voicemail tree, it's an answer.
          </p>
        </div>

        <div className="problem-grid">
          {PROBLEMS.map((p, i) => (
            <div className="problem-card" key={i}>
              <div className="problem-stat">
                {p.stat}<span className="unit">{p.unit}</span>
              </div>
              <h3>{p.title}</h3>
              <p>{p.body}</p>
              <div className="cite">{p.cite}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const STEPS = [
  {
    n: "01",
    title: "A patient calls.",
    body: "Premura picks up on the first ring in a voice you choose, using phrasing trained on your own recorded calls. No hold music, no menu trees.",
    visual: (
      <>
        <div className="line"><span className="t">00:01</span><span className="ca">"Hi, is this Relaxation Dental?"</span></div>
        <div className="line"><span className="t">00:02</span><span className="ag">"It is — what can I help you with?"</span></div>
      </>
    ),
  },
  {
    n: "02",
    title: "It schedules, your way.",
    body: "Premura follows your scheduling rules — block patterns, provider preferences, new-patient gates — picks an opening, and confirms with the caller.",
    visual: (
      <>
        <div className="line"><span className="t">→</span><span className="ag">checking openings…</span></div>
        <div className="line"><span className="t">✓</span><span className="ca">Tue 2:15pm · Dr. Patel</span></div>
        <div className="line"><span className="t">✓</span><span className="ca">SMS confirmation sent</span></div>
      </>
    ),
  },
  {
    n: "03",
    title: "Humans handle what humans should.",
    body: "Emergencies, insurance disputes, anything off-script, Premura warm-transfers to your team with full context.",
    visual: (
      <>
        <div className="line"><span className="t">⚠</span><span className="ag">Emergency · ringing front desk</span></div>
        <div className="line"><span className="t">→</span><span className="ca">Patient on line 2</span></div>
        <div className="line"><span className="t">📋</span><span className="ca">Notes attached</span></div>
      </>
    ),
  },
];

const PILLARS = [
  {
    label: "Voice",
    title: "Pick a voice. Or clone yours.",
    body: "Choose from a library of natural voices, or train a custom voice from a few minutes of your front-desk team. Patients hear someone who sounds like your practice.",
    visual: (
      <div className="pillar-voices">
        <div className="voice-chip selected"><span className="vd"></span>Maren · warm, unhurried</div>
        <div className="voice-chip"><span className="vd"></span>Rae · brisk, friendly</div>
        <div className="voice-chip"><span className="vd"></span>Theo · calm, low-register</div>
        <div className="voice-chip custom"><span className="vd"></span>+ Clone from your calls</div>
      </div>
    ),
  },
  {
    label: "Tone & scripts",
    title: "Your phrasing, not ours.",
    body: "Train Premura on your own recorded calls so it picks up the way your team handles insurance, emergencies, and small talk. Adjust tone with sliders: formal to casual, brisk to leisurely.",
    visual: <ToneSliders />,
  },
  {
    label: "Scheduling rules",
    title: "Booking that respects your day.",
    body: "Map block patterns, provider preferences, visit-type rules, new-patient gates, and same-day emergency slots. Premura schedules within the lines you've drawn.",
    visual: (
      <div className="pillar-rules">
        <div className="rule"><span className="rd ok"></span><span>Hygiene · 60 min · Mon–Thu</span></div>
        <div className="rule"><span className="rd ok"></span><span>New-patient · require insurance verify</span></div>
        <div className="rule"><span className="rd ok"></span><span>Emergencies → Dr. Patel only</span></div>
        <div className="rule"><span className="rd warn"></span><span>Don't double-book Fridays after 3</span></div>
      </div>
    ),
  },
  {
    label: "Knowledge & integrations",
    title: "It knows what your team knows.",
    body: "Upload your fee schedule, insurance lists, post-op instructions, and FAQs. Connects to Open Dental, Eaglesoft, Dentrix, and your phone provider.",
    visual: (
      <div className="pillar-kb">
        <div className="kb-tag">Fee schedule.pdf</div>
        <div className="kb-tag">Insurance list 2026.csv</div>
        <div className="kb-tag">Post-op · crown</div>
        <div className="kb-tag">Open Dental · live</div>
        <div className="kb-tag">Telnyx · routed</div>
      </div>
    ),
  },
];

function ToneSliders() {
  const [vals, setVals] = React.useState({
    formality: 32,
    pace: 50,
    empathy: 74,
    patience: 60,
  });
  const [userTouched, setUserTouched] = React.useState(false);

  const labelFor = (key, v) => {
    if (key === 'formality') return v < 30 ? 'Warm' : v < 65 ? 'Even' : 'Formal';
    if (key === 'pace')       return v < 35 ? 'Calm' : v < 65 ? 'Even' : 'Brisk';
    if (key === 'empathy')    return v < 35 ? 'Light' : v < 70 ? 'Warm' : 'High';
    if (key === 'patience')   return v < 35 ? 'Quick' : v < 70 ? 'Patient' : 'Generous';
    return '';
  };

  // Auto-demo: nudges the sliders so visitors see them move.
  // Stops permanently once the user drags any slider.
  React.useEffect(() => {
    if (userTouched) return;
    const seq = [
      { formality: 32, pace: 50, empathy: 74, patience: 60 },
      { formality: 58, pace: 32, empathy: 82, patience: 78 },
      { formality: 20, pace: 72, empathy: 60, patience: 40 },
      { formality: 45, pace: 55, empathy: 88, patience: 70 },
    ];
    let i = 0;
    const id = setInterval(() => {
      i = (i + 1) % seq.length;
      setVals(seq[i]);
    }, 3200);
    return () => clearInterval(id);
  }, [userTouched]);

  const onUserChange = (key, value) => {
    setUserTouched(true);
    setVals(v => ({ ...v, [key]: value }));
  };

  const rows = [
    { key: 'formality', label: 'Formality' },
    { key: 'pace',      label: 'Pace' },
    { key: 'empathy',   label: 'Empathy' },
    { key: 'patience',  label: 'Patience' },
  ];

  return (
    <div className={`pillar-sliders${userTouched ? ' touched' : ''}`}>
      {rows.map(({ key, label }) => (
        <div className="slider-row" key={key}>
          <span className="srk">{label}</span>
          <div className="track">
            <div className="track-fill" style={{ width: `${vals[key]}%` }}></div>
            <input
              type="range"
              min="0" max="100" step="1"
              value={vals[key]}
              onChange={(e) => onUserChange(key, +e.target.value)}
              aria-label={label}
            />
            <div className="thumb" style={{ left: `${vals[key]}%` }}></div>
          </div>
          <span className="srv">{labelFor(key, vals[key])}</span>
        </div>
      ))}
    </div>
  );
}


function Customize() {
  return (
    <section className="section" id="customize">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Built around your practice</span>
          <h2>Not a one-size-fits-all dental bot. <span className="serif">Yours.</span></h2>
          <p className="lede">
            Most dental AI tools come pre-baked with a generic voice and a generic
            script. Premura is the opposite, every part is tuned to how your
            practice already runs.
          </p>
        </div>

        <div className="pillar-grid">
          {PILLARS.map((p, i) => (
            <div className="pillar-card" key={i}>
              <span className="eyebrow pillar-eyebrow">{p.label}</span>
              <h3>{p.title}</h3>
              <p>{p.body}</p>
              <div className="pillar-visual">{p.visual}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function HowItWorks() {
  return (
    <section className="section alt" id="how">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">How it works</span>
          <h2>Calm, competent, and <span className="serif">always</span> on the line.</h2>
          <p className="lede">
            Premura sounds like a great front-desk hire who happened to memorize your
            knowledge base on day one. Three things happen on every call.
          </p>
        </div>

        <div className="how-grid">
          {STEPS.map((s, i) => (
            <div className="how-step" key={i}>
              <span className="step-no">{s.n}</span>
              <h3>{s.title}</h3>
              <p>{s.body}</p>
              <div className="how-visual">{s.visual}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function CTABand() {
  return (
    <section className="cta-band">
      <div className="container cta-band-inner">
        <div>
          <h2>Bring Premura to your <span className="serif">practice.</span></h2>
          <p>
            We're onboarding a small group of design-partner practices. Tell us a
            bit about your front desk and we'll be in touch.
          </p>
        </div>
        <Waitlist dark />
      </div>
    </section>
  );
}

function SiteFooter() {
  return (
    <footer className="site-foot" id="footer">
      <div className="container">
        <div className="foot-grid">
          <div className="foot-brand">
            <a href="#" className="nav-brand">
              <svg className="mark" viewBox="0 0 200 200" aria-hidden="true">
                <g transform="translate(70, 100)">
                  <circle cx="0" cy="0" r="10" fill="#E07A66"></circle>
                  <path d="M 24 -24 Q 40 0 24 24" fill="none" stroke="#0F4C5C" strokeWidth="6" strokeLinecap="round"/>
                  <path d="M 46 -46 Q 70 0 46 46" fill="none" stroke="#0F4C5C" strokeWidth="6" strokeLinecap="round" opacity="0.7"/>
                  <path d="M 68 -68 Q 100 0 68 68" fill="none" stroke="#0F4C5C" strokeWidth="6" strokeLinecap="round" opacity="0.4"/>
                </g>
              </svg>
              <span className="word">premura</span>
            </a>
            <p className="copy">An AI receptionist for dental practices. Built to be a teammate, not a chatbot.</p>
          </div>
          <div className="foot-col">
            <h5>Product</h5>
            <a href="#problem">Missed calls</a>
            <a href="#customize">Tuned to you</a>
            <a href="#how">On every call</a>
            <a href="#waitlist">Request access</a>
          </div>
          <div className="foot-col">
            <h5>Legal &amp; Compliance</h5>
            <a href="#">MSA <span className="badge-soft">PDF</span></a>
            <a href="#">BAA <span className="badge-soft">PDF</span></a>
            <a href="#">Privacy policy</a>
            <a href="#">Security overview</a>
          </div>
          <div className="foot-col">
            <h5>Contact</h5>
            <a href="mailto:hello@premura.ai">hello@premura.ai</a>
            <a href="#">Status</a>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 Premura, Inc. — HIPAA-compliant infrastructure.</span>
          <div className="legal-links">
            <a href="#">Terms</a>
            <a href="#">Privacy</a>
            <a href="#">DPA</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, Problem, Customize, HowItWorks, CTABand, SiteFooter, ToneSliders });
