/* global React, ProjectImage, CONTACT_EMAIL, CONTACT_PHONE, MAIL_HREF, TEL_HREF */
// About + Contact pages

const EXPERTISE = [
  ["Mimari Proje Tasarımı", "Konuttan ticari yapıya; ihtiyaç programından ruhsat projesine kadar mimari tasarımın tüm aşamaları."],
  ["Uygulama Projeleri", "Tasarımı şantiyeye taşıyan detay çözümleri, mahal listeleri ve uygulama çizimleri."],
  ["3D Görselleştirme ve Animasyon", "Fotogerçekçi mimari görselleştirme; tasarımı inşaattan önce deneyimleme imkânı."],
  ["Restorasyon Projeleri", "Tarihi ve tescilli yapıların korunmasına yönelik projelendirme ve kurul süreçleri."],
  ["Rölöve — Restitüsyon — Restorasyon", "Mevcut yapının belgelenmesi, özgün halinin araştırılması ve koruma projesinin hazırlanması."],
  ["Şantiye Takibi ve Proje Yönetimi", "Uygulamanın projeye uygun yürümesi için düzenli şantiye kontrolü ve süreç yönetimi."],
  ["Villa ve Konut Projeleri", "Müstakil konut ve villa tasarımı; arsaya, iklime ve kullanıcıya özel çözümler."],
  ["Tadilat", "Mevcut konut ve iş yerlerinde yenileme, mekân düzenlemesi ve iç mekân tadilat projeleri."],
];

function About({ projects, navigate }) {
  return (
    <div className="page-in">
      <header style={{ padding: "72px 32px 56px", borderBottom: "1px solid var(--line-soft)" }}>
        <div className="t-mono" style={{ color: "var(--muted)" }}>Yüksek Mimar · Restorasyon Uzmanı · Bergama, İzmir</div>
        <h1 className="t-display" style={{ fontSize: "clamp(64px, 8vw, 132px)", margin: "24px 0 0", maxWidth: 1200, lineHeight: 0.95 }}>
          <em>Gizem Güleç</em>
        </h1>
      </header>

      <section style={{ padding: "72px 32px", display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: 64 }}>
        <span className="t-mono" style={{ color: "var(--muted)" }}>(Hakkımda)</span>
        <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
          <p style={{ fontSize: 22, lineHeight: 1.5, margin: 0, fontFamily: "var(--font-display)", textWrap: "pretty" }}>
            2014'ten bu yana Bergama'da mimarlık, tasarım ve restorasyon alanlarında çalışıyorum.
          </p>
          <p style={{ fontSize: 16, lineHeight: 1.65, margin: 0, color: "var(--muted)", textWrap: "pretty" }}>
            Konut ve villa projelerinde mimari tasarım, uygulama projeleri, 3B görselleştirme
            ve şantiye takibi; tarihi yapılarda rölöve, restitüsyon ve restorasyon projeleri
            hazırlıyorum. Projelerin ruhsat ve kurul süreçlerini de yürütüyorum.
          </p>
          <p style={{ fontSize: 16, lineHeight: 1.65, margin: 0, color: "var(--muted)", textWrap: "pretty" }}>
            Her projeyi ilk görüşmeden teslime kadar kendim takip ediyorum. İşverenle düzenli
            iletişim ve şantiyede birebir kontrol, çalışma yöntemimin temelini oluşturuyor.
          </p>
        </div>
      </section>

      <section style={{ padding: "72px 32px", background: "var(--bg-alt)", borderTop: "1px solid var(--line-soft)", borderBottom: "1px solid var(--line-soft)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 64 }}>
          <h2 className="t-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: 0, fontStyle: "italic" }}>Uzmanlık Alanları</h2>
          <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
            {EXPERTISE.map(([title, desc], i) => (
              <li key={title} style={{
                display: "grid",
                gridTemplateColumns: "100px 1fr",
                gap: 24,
                padding: "20px 0",
                borderTop: "1px solid var(--line-soft)",
                alignItems: "baseline",
              }}>
                <span className="t-mono t-num" style={{ fontSize: 18, color: "var(--accent)" }}>{String(i + 1).padStart(2, "0")}</span>
                <div>
                  <h3 style={{ fontSize: 18, fontFamily: "var(--font-display)", fontWeight: 400, margin: 0 }}>{title}</h3>
                  <p style={{ fontSize: 14, lineHeight: 1.6, color: "var(--muted)", margin: "6px 0 0", textWrap: "pretty" }}>{desc}</p>
                </div>
              </li>
            ))}
            <li style={{ borderTop: "1px solid var(--line-soft)" }} />
          </ul>
        </div>
      </section>
    </div>
  );
}
window.EXPERTISE = EXPERTISE;

const TURNSTILE_SITEKEY = "0x4AAAAAAEYs5uIze0vazmBc";

// Çalışma saatleri: Pzt–Cmt 10:00–18:00 (Türkiye saati), Pazar kapalı.
// Ziyaretçinin saat diliminden bağımsız olsun diye İstanbul saatiyle bakılır.
function isOpenNow() {
  try {
    const f = new Intl.DateTimeFormat("tr-TR", {
      timeZone: "Europe/Istanbul",
      weekday: "short", hour: "2-digit", hour12: false,
    });
    const parts = Object.fromEntries(f.formatToParts(new Date()).map((p) => [p.type, p.value]));
    const day = (parts.weekday || "").toLowerCase();
    const hour = parseInt(parts.hour, 10);
    if (day.startsWith("paz") && !day.startsWith("pazartesi")) return false; // Pazar
    return hour >= 10 && hour < 18;
  } catch {
    return false;
  }
}

function Contact({ navigate }) {
  const emptyForm = { name: "", email: "", phone: "", project: "Mimari Proje", message: "", website: "" };
  const [form, setForm] = React.useState(emptyForm);
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const setF = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  // Turnstile widget — form her göründüğünde render edilir, kapanınca kaldırılır
  const tsRef = React.useRef(null);
  const tsId = React.useRef(null);
  const formVisible = status !== "sent";
  React.useEffect(() => {
    if (!formVisible) return;
    let cancelled = false;
    const tryRender = () => {
      if (cancelled) return;
      if (window.turnstile && tsRef.current && tsId.current === null) {
        tsId.current = window.turnstile.render(tsRef.current, {
          sitekey: TURNSTILE_SITEKEY,
          action: "contact",
          theme: "auto",
        });
      } else if (!window.turnstile) {
        setTimeout(tryRender, 250);
      }
    };
    tryRender();
    return () => {
      cancelled = true;
      if (tsId.current !== null && window.turnstile) {
        try { window.turnstile.remove(tsId.current); } catch {}
      }
      tsId.current = null;
    };
  }, [formVisible]);

  const submit = async (e) => {
    e.preventDefault();
    if (status === "sending") return;
    setStatus("sending");
    const token =
      tsId.current !== null && window.turnstile
        ? window.turnstile.getResponse(tsId.current)
        : "";
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ...form, "cf-turnstile-response": token }),
      });
      const data = await res.json().catch(() => ({}));
      setStatus(res.ok && data.ok ? "sent" : "error");
    } catch {
      setStatus("error");
    }
    // Token tek kullanımlık — sonuç ne olursa olsun widget'ı sıfırla
    if (tsId.current !== null && window.turnstile) {
      try { window.turnstile.reset(tsId.current); } catch {}
    }
  };

  return (
    <div className="page-in">
      <header style={{ padding: "72px 32px 0" }}>
        <div className="t-mono" style={{ color: "var(--muted)" }}>İletişim</div>
        <h1 className="t-display" style={{ fontSize: "clamp(64px, 8vw, 132px)", margin: "24px 0 0", lineHeight: 0.95 }}>
          Projenizi <em>konuşalım</em>.
        </h1>
      </header>

      <section style={{ padding: "72px 32px", display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 64 }}>
        <div>
          {status === "sent" ? (
            <div style={{ padding: "48px 0" }}>
              <div className="t-mono" style={{ color: "var(--accent)", marginBottom: 16 }}>● Mesaj alındı</div>
              <p className="t-display" style={{ fontSize: 32, margin: 0, fontStyle: "italic", lineHeight: 1.3 }}>
                Teşekkürler, {form.name || "değerli okuyucu"}. En kısa sürede size döneceğiz.
              </p>
              <button
                onClick={() => { setStatus("idle"); setForm(emptyForm); }}
                className="t-mono"
                style={{ marginTop: 32, padding: "12px 0", borderBottom: "1px solid var(--fg)" }}
              >
                Yeni mesaj yaz →
              </button>
            </div>
          ) : (
            <form
              onSubmit={submit}
              style={{ display: "flex", flexDirection: "column", gap: 28 }}
            >
              {/* Bal küpü — insanlar görmez, botlar doldurur */}
              <input
                type="text"
                value={form.website}
                onChange={setF("website")}
                autoComplete="off"
                tabIndex={-1}
                aria-hidden="true"
                style={{ position: "absolute", left: -9999, width: 1, height: 1, opacity: 0 }}
              />
              <FormField label="01 · İsim">
                <input value={form.name} onChange={setF("name")} required style={inputStyle} placeholder="Adınız" />
              </FormField>
              <FormField label="02 · E-posta">
                <input type="email" value={form.email} onChange={setF("email")} required style={inputStyle} placeholder="ornek@posta.com" />
              </FormField>
              <FormField label="03 · Telefon">
                <input
                  type="tel"
                  value={form.phone}
                  onChange={setF("phone")}
                  style={inputStyle}
                  placeholder="05xx xxx xx xx"
                  autoComplete="tel"
                  inputMode="tel"
                />
              </FormField>
              <FormField label="04 · Proje türü">
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {["Mimari Proje", "Villa / Konut", "Restorasyon", "Rölöve", "3D Görselleştirme", "Şantiye Takibi", "Diğer"].map((t) => (
                    <button
                      key={t}
                      type="button"
                      className="tag"
                      data-active={form.project === t}
                      onClick={() => setForm((f) => ({ ...f, project: t }))}
                    >
                      {t}
                    </button>
                  ))}
                </div>
              </FormField>
              <FormField label="05 · Kısaca anlatın">
                <textarea
                  value={form.message}
                  onChange={setF("message")}
                  required
                  rows="6"
                  style={{ ...inputStyle, resize: "vertical", minHeight: 140 }}
                  placeholder="Proje yeri, ölçeği, takvimi…"
                />
              </FormField>
              {/* Turnstile bot doğrulaması */}
              <div ref={tsRef} />
              <p style={{ margin: 0, fontSize: 12, lineHeight: 1.5, color: "var(--muted)", maxWidth: 480 }}>
                Formu gönderdiğinizde; ad, e-posta ve mesaj bilgileriniz yalnızca
                talebinize dönüş yapılması amacıyla işlenir, üçüncü kişilerle
                paylaşılmaz ve pazarlama amacıyla kullanılmaz.
              </p>
              <button
                type="submit"
                className="t-mono"
                disabled={status === "sending"}
                style={{
                  alignSelf: "start",
                  padding: "14px 24px",
                  background: "var(--fg)",
                  color: "var(--bg)",
                  borderRadius: 999,
                  marginTop: 8,
                  opacity: status === "sending" ? 0.6 : 1,
                  cursor: status === "sending" ? "wait" : "pointer",
                }}
              >
                {status === "sending" ? "Gönderiliyor…" : "Mesajı gönder →"}
              </button>
              {status === "error" && (
                <p style={{ margin: 0, fontSize: 14, color: "var(--accent)" }}>
                  Mesaj gönderilemedi. Lütfen tekrar deneyin ya da bize telefonla ulaşın:{" "}
                  <a href={TEL_HREF} style={{ borderBottom: "1px solid var(--accent)" }}>{CONTACT_PHONE}</a>
                </p>
              )}
            </form>
          )}
        </div>

        <aside style={{ display: "flex", flexDirection: "column", gap: 36 }}>
          <div>
            <div className="t-meta">Ofis</div>
            <div style={{ marginTop: 8, fontSize: 16, lineHeight: 1.5 }}>
              Ertuğrul Mh. Park Otel Sk.<br />
              No: 9 · D: 3<br />
              Bergama, İzmir
            </div>
          </div>
          <div>
            <div className="t-meta">Sorumlu Mimar</div>
            <div style={{ marginTop: 8, fontSize: 16, lineHeight: 1.5 }}>
              Gizem Güleç<br />
              <span style={{ color: "var(--muted)", fontSize: 14 }}>Yüksek Mimar · Restorasyon Uzmanı</span>
            </div>
          </div>
          <div>
            <div className="t-meta">Telefon</div>
            <div style={{ marginTop: 8, fontSize: 16, fontFamily: "var(--font-mono)" }}>
              <a href={TEL_HREF} style={{ borderBottom: "1px solid var(--line)" }}>{CONTACT_PHONE}</a>
            </div>
          </div>
          <div>
            <div className="t-meta">E-posta</div>
            <div style={{ marginTop: 8, fontSize: 16, fontFamily: "var(--font-mono)", wordBreak: "break-all" }}>
              <a href={MAIL_HREF} style={{ borderBottom: "1px solid var(--line)" }}>{CONTACT_EMAIL}</a>
            </div>
          </div>
          <div>
            <div className="t-meta">Sosyal</div>
            <div style={{ marginTop: 8, display: "flex", gap: 16, fontSize: 14 }}>
              <a style={{ borderBottom: "1px solid var(--line)" }}>Instagram</a>
              <a style={{ borderBottom: "1px solid var(--line)" }}>Are.na</a>
              <a style={{ borderBottom: "1px solid var(--line)" }}>LinkedIn</a>
            </div>
          </div>
          <div style={{ marginTop: 24, padding: 20, border: "1px solid var(--line)", borderRadius: 4 }}>
            <div className="t-mono" style={{ color: isOpenNow() ? "var(--accent)" : "var(--muted)" }}>
              ● {isOpenNow() ? "Şu an açık" : "Şu an kapalı"}
            </div>
            <div style={{ marginTop: 8, fontSize: 14, color: "var(--muted)" }}>
              Pzt — Cmt · 10:00 — 18:00<br />
              Pazar · kapalı
            </div>
          </div>
        </aside>
      </section>
    </div>
  );
}

const inputStyle = {
  width: "100%",
  padding: "14px 0",
  fontSize: 18,
  fontFamily: "var(--font-display)",
  background: "transparent",
  border: 0,
  borderBottom: "1px solid var(--line)",
  color: "var(--fg)",
  outline: "none",
};

function FormField({ label, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <span className="t-meta">{label}</span>
      {children}
    </label>
  );
}

window.About = About;
window.Contact = Contact;
