/* global React */
const { useState, useEffect, useMemo } = React;

function ContactPage({ navigate }) {
  const today = new Date();
  today.setHours(0,0,0,0);
  const [viewMonth, setViewMonth] = useState(new Date(today.getFullYear(), today.getMonth(), 1));
  const [selDate, setSelDate] = useState(null);
  const [selSlot, setSelSlot] = useState(null);
  const [booked, setBooked] = useState(false);
  const [form, setForm] = useState({ name: "", email: "", company: "", topic: "Process automation", notes: "" });

  // generate days
  const days = useMemo(() => {
    const first = new Date(viewMonth.getFullYear(), viewMonth.getMonth(), 1);
    const startDow = (first.getDay() + 6) % 7; // monday-first
    const daysInMonth = new Date(viewMonth.getFullYear(), viewMonth.getMonth()+1, 0).getDate();
    const cells = [];
    for (let i = 0; i < startDow; i++) cells.push(null);
    for (let d = 1; d <= daysInMonth; d++) {
      const date = new Date(viewMonth.getFullYear(), viewMonth.getMonth(), d);
      const dow = date.getDay();
      const isPast = date < today;
      const isWeekend = dow === 0 || dow === 6;
      const hasSlot = !isPast && !isWeekend;
      cells.push({ date, hasSlot, disabled: isPast || isWeekend });
    }
    while (cells.length % 7 !== 0) cells.push(null);
    return cells;
  }, [viewMonth]);

  const slots = useMemo(() => {
    if (!selDate) return [];
    // pseudo-random availability per day
    const seed = selDate.getDate() + selDate.getMonth();
    const all = ["09:00","09:30","10:00","10:30","11:00","11:30","13:00","13:30","14:00","14:30","15:00","15:30","16:00","16:30"];
    return all.map((s, i) => ({ time: s, taken: ((i * (seed+3)) % 5) === 0 }));
  }, [selDate]);

  const monthLabel = viewMonth.toLocaleString("en-US", { month: "long", year: "numeric" });
  const dows = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];

  function shiftMonth(dir) {
    const next = new Date(viewMonth.getFullYear(), viewMonth.getMonth()+dir, 1);
    if (next < new Date(today.getFullYear(), today.getMonth(), 1)) return;
    setViewMonth(next);
    setSelDate(null);
    setSelSlot(null);
  }

  function confirm() {
    if (!selDate || !selSlot) return;
    setBooked(true);
  }

  function reset() {
    setBooked(false); setSelDate(null); setSelSlot(null);
  }

  return (
    <div className="page page-enter">
      <section className="container hero" style={{paddingBottom: 40}}>
        <span className="eyebrow reveal">Contact</span>
        <h1 className="reveal" style={{marginTop: 14}}>
          Book a <span className="accent-line">discovery call.</span>
        </h1>
        <p className="lead reveal" style={{marginTop: 22}}>
          Pick a 30-minute slot. We'll send a calendar invite and a short prep doc so the call is useful from minute one.
        </p>
      </section>

      <section className="container block" style={{paddingTop: 12}}>
        <div className="contact-grid reveal">
          <div className="info-card">
            <h3>Reach us</h3>
            <div className="info-row">
              <div className="ico">✉</div>
              <div>
                <div className="k">Email</div>
                <div className="v">hello@aiagency.my</div>
              </div>
            </div>
            <div className="info-row">
              <div className="ico">☏</div>
              <div>
                <div className="k">Phone</div>
                <div className="v">+60 3 1234 5678</div>
              </div>
            </div>
            <div className="info-row">
              <div className="ico">⌖</div>
              <div>
                <div className="k">Studio</div>
                <div className="v">Level 14, Menara KH<br/>Jalan Sultan Ismail, KL</div>
              </div>
            </div>
            <div className="info-row">
              <div className="ico">⏱</div>
              <div>
                <div className="k">Response time</div>
                <div className="v">Within 1 working day</div>
              </div>
            </div>
            <div style={{marginTop: 18, paddingTop: 18, borderTop: "1px solid var(--line)"}}>
              <div style={{fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--text-muted)"}}>
                30-min discovery call · Free
              </div>
            </div>
          </div>

          <div>
            {!booked ? (
              <div className="calendar">
                <div className="cal-head">
                  <div className="cal-month">{monthLabel}</div>
                  <div className="cal-nav">
                    <button onClick={()=>shiftMonth(-1)} aria-label="Previous month">‹</button>
                    <button onClick={()=>shiftMonth(1)} aria-label="Next month">›</button>
                  </div>
                </div>
                <div className="cal-grid">
                  {dows.map(d => <div key={d} className="cal-dow">{d}</div>)}
                  {days.map((c, i) => {
                    if (!c) return <div key={i}></div>;
                    const isToday = c.date.getTime() === today.getTime();
                    const isSel = selDate && c.date.getTime() === selDate.getTime();
                    return (
                      <button
                        key={i}
                        className={"cal-day"
                          + (c.hasSlot ? " has-slot" : "")
                          + (c.disabled ? " disabled" : "")
                          + (isToday ? " today" : "")
                          + (isSel ? " selected" : "")}
                        disabled={c.disabled}
                        onClick={()=>{ setSelDate(c.date); setSelSlot(null); }}
                      >
                        {c.date.getDate()}
                      </button>
                    );
                  })}
                </div>
                {selDate && (
                  <div className="slots">
                    <div className="slots-head">
                      <div className="date">{selDate.toLocaleDateString("en-US", { weekday:"long", month:"long", day:"numeric" })}</div>
                      <div className="tz">GMT+8 · Kuala Lumpur</div>
                    </div>
                    <div className="slot-grid">
                      {slots.map(s => (
                        <button key={s.time}
                          className={"slot" + (selSlot === s.time ? " selected" : "")}
                          disabled={s.taken}
                          onClick={()=>setSelSlot(s.time)}>
                          {s.time}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
                {selDate && selSlot && (
                  <div style={{marginTop: 22}}>
                    <div className="field-row">
                      <div className="field">
                        <label>Name</label>
                        <input value={form.name} onChange={e=>setForm({...form, name:e.target.value})} placeholder="Your name" />
                      </div>
                      <div className="field">
                        <label>Email</label>
                        <input type="email" value={form.email} onChange={e=>setForm({...form, email:e.target.value})} placeholder="you@company.com" />
                      </div>
                    </div>
                    <div className="field-row">
                      <div className="field">
                        <label>Company</label>
                        <input value={form.company} onChange={e=>setForm({...form, company:e.target.value})} placeholder="Company name" />
                      </div>
                      <div className="field">
                        <label>Topic</label>
                        <select value={form.topic} onChange={e=>setForm({...form, topic:e.target.value})}>
                          <option>Process automation</option>
                          <option>Custom AI agent</option>
                          <option>Tech talk / workshop</option>
                          <option>Custom website / tool</option>
                          <option>Not sure yet</option>
                        </select>
                      </div>
                    </div>
                    <div className="field">
                      <label>What's the bottleneck? (optional)</label>
                      <textarea rows={3} value={form.notes} onChange={e=>setForm({...form, notes:e.target.value})} placeholder="A sentence or two helps us prep."></textarea>
                    </div>
                    <div className="confirm">
                      <div className="summary">
                        <strong>{selDate.toLocaleDateString("en-US", { weekday:"short", month:"short", day:"numeric" })} · {selSlot}</strong>
                        <span style={{color:"var(--text-muted)"}}> — 30 min · GMT+8</span>
                      </div>
                      <button className="btn btn-accent" onClick={confirm} disabled={!form.name || !form.email}>
                        Confirm booking <span className="arrow">→</span>
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <div className="calendar">
                <div className="booked">
                  <div className="check"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="4 12 10 18 20 6"/></svg></div>
                  <h3>You're booked.</h3>
                  <p>{selDate.toLocaleDateString("en-US", { weekday:"long", month:"long", day:"numeric" })} at {selSlot} (GMT+8)</p>
                  <p style={{marginTop: 6}}>Calendar invite on its way to <strong style={{color: "var(--bg)"}}>{form.email}</strong>.</p>
                  <button className="btn btn-ghost" style={{marginTop: 22, color: "var(--bg)", borderColor: "rgba(255,255,255,0.3)"}} onClick={reset}>Book another</button>
                </div>
              </div>
            )}
          </div>
        </div>
      </section>
    </div>
  );
}

window.ContactPage = ContactPage;
