/* global React, Icon, useReveal */
const { useState: useStateCP } = React;

// ===== Contact =====
const ContactPage = ({ navigate }) => {
  useReveal();
  const [form, setForm] = useStateCP({ name: "", email: "", topic: "support", message: "", website: "" });
  const [errors, setErrors] = useStateCP({});
  const [sent, setSent] = useStateCP(false);
  const [submitting, setSubmitting] = useStateCP(false);
  const [serverError, setServerError] = useStateCP(null);

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Please tell us your name.";
    if (!form.email.trim()) e.email = "We need an email to reply to.";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "That doesn't look right.";
    if (!form.message.trim() || form.message.trim().length < 8) e.message = "A few more words would help.";
    return e;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    setServerError(null);
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) return;
    setSubmitting(true);
    try {
      const res = await fetch("/send.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        if (data.errors) {
          setErrors(data.errors);
        } else {
          setServerError(data.error || "Couldn't send right now. Email apps@cryptdapp.com directly.");
        }
        setSubmitting(false);
        return;
      }
      setSent(true);
      setForm({ name: "", email: "", topic: "support", message: "", website: "" });
      setTimeout(() => setSent(false), 4500);
    } catch (err) {
      setServerError("Network error. Email apps@cryptdapp.com directly.");
    } finally {
      setSubmitting(false);
    }
  };

  const upd = (k) => (ev) => {
    setForm(f => ({ ...f, [k]: ev.target.value }));
    if (errors[k]) setErrors(e => ({ ...e, [k]: undefined }));
  };

  return (
    <div className="page-enter">
      <section className="section">
        <div className="container container-narrow">
          <div className="reveal in" style={{textAlign:"center",marginBottom:48}}>
            <div className="eyebrow">CONTACT</div>
            <h1 className="display" style={{fontSize:"clamp(40px, 5vw, 64px)",margin:"14px 0 16px"}}>
              <span className="gradient-text">Say hello.</span>
            </h1>
            <p style={{fontSize:18,color:"var(--text-2)",maxWidth:520,margin:"0 auto"}}>
              Bug reports, feature requests, partnership ideas, app store complaints — send them all here. A real person reads every message, usually within a day.
            </p>
          </div>

          <div className="reveal">
            <div className="form-wrap">
              <form onSubmit={submit} noValidate>
                <div className="form-row">
                  <div className="field">
                    <label>Name</label>
                    <input type="text" value={form.name} onChange={upd("name")} className={errors.name ? "error" : ""} placeholder="What should we call you?"/>
                    {errors.name && <div className="field-error">{errors.name}</div>}
                  </div>
                  <div className="field">
                    <label>Email</label>
                    <input type="email" value={form.email} onChange={upd("email")} className={errors.email ? "error" : ""} placeholder="you@somewhere.com"/>
                    {errors.email && <div className="field-error">{errors.email}</div>}
                  </div>
                </div>
                <div className="field" style={{marginBottom: 20}}>
                  <label>Topic</label>
                  <select value={form.topic} onChange={upd("topic")}>
                    <option value="support">App support / bug</option>
                    <option value="feature">Feature request</option>
                    <option value="press">Press / media</option>
                    <option value="business">Business / partnership</option>
                    <option value="privacy">Privacy question</option>
                    <option value="other">Something else</option>
                  </select>
                </div>
                <div className="field" style={{marginBottom: 24}}>
                  <label>Message</label>
                  <textarea value={form.message} onChange={upd("message")} className={errors.message ? "error" : ""} placeholder="Tell us what's on your mind..." rows={6}/>
                  {errors.message && <div className="field-error">{errors.message}</div>}
                </div>
                {/* Honeypot — hidden from real users, bots fill it in */}
                <div style={{position:"absolute",left:"-9999px",top:"auto",width:1,height:1,overflow:"hidden"}} aria-hidden="true">
                  <label>Website</label>
                  <input type="text" tabIndex={-1} autoComplete="off" value={form.website} onChange={upd("website")}/>
                </div>
                {serverError && <div className="field-error" style={{marginBottom: 16}}>{serverError}</div>}
                <div style={{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"}}>
                  <button type="submit" className="btn btn-primary" disabled={submitting} style={submitting ? {opacity:0.7, cursor:"wait"} : {}}>
                    <Icon name="send" size={15}/> {submitting ? "Sending…" : "Send message"}
                  </button>
                  <span style={{fontSize:13,color:"var(--muted)"}}>Goes straight to apps@cryptdapp.com.</span>
                </div>
              </form>
            </div>
          </div>

          {/* Direct contact */}
          <div className="reveal" style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:16,marginTop:32}}>
            {[
              {icon:"mail", label: "Email", value: "apps@cryptdapp.com", href: "mailto:apps@cryptdapp.com"},
              {icon:"twitter", label: "Twitter", value: "@cryptdapp", href: "https://twitter.com/cryptdapp"},
              {icon:"instagram", label: "Instagram", value: "@cryptdapp", href: "https://instagram.com/cryptdapp"},
            ].map(c => (
              <a key={c.label} href={c.href} target={c.href.startsWith("http") ? "_blank" : undefined} rel="noopener noreferrer" style={{
                padding: 20, border: "1px solid var(--line)", borderRadius: 14,
                background: "rgba(255,255,255,0.02)", display: "flex", alignItems: "center", gap: 14,
                cursor: "pointer", transition: "all 200ms",
                textDecoration: "none", color: "inherit"
              }}
              onMouseEnter={e => e.currentTarget.style.background = "rgba(255,255,255,0.05)"}
              onMouseLeave={e => e.currentTarget.style.background = "rgba(255,255,255,0.02)"}>
                <div style={{width: 38, height: 38, borderRadius: 9, background: "rgba(168,85,247,0.12)", border: "1px solid rgba(168,85,247,0.3)", display: "grid", placeItems: "center", color: "var(--brand-2)"}}>
                  <Icon name={c.icon} size={18} stroke={1.8}/>
                </div>
                <div>
                  <div style={{fontSize:11,color:"var(--muted)",letterSpacing:"0.1em",textTransform:"uppercase",marginBottom:2}}>{c.label}</div>
                  <div style={{fontSize:14,fontWeight:600}}>{c.value}</div>
                </div>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Toast */}
      <div className={"toast" + (sent ? " show" : "")}>
        <Icon name="check" size={16} style={{verticalAlign:"middle",marginRight:8}}/>
        Message sent. We'll be in touch shortly.
      </div>

      <style>{`
        @media (max-width: 760px) {
          .field-error + .form-row, .form-row + * { }
        }
      `}</style>
    </div>
  );
};

// ===== Privacy =====
const PrivacyPage = () => {
  useReveal();
  const sections = [
    { id: "overview", title: "Overview" },
    { id: "what-we-collect", title: "What we collect" },
    { id: "what-we-don't", title: "What we don't collect" },
    { id: "where-data-lives", title: "Where data lives" },
    { id: "third-parties", title: "Third parties" },
    { id: "your-rights", title: "Your rights" },
    { id: "changes", title: "Changes to this policy" },
    { id: "contact", title: "How to reach us" },
  ];

  return (
    <div className="page-enter legal">
      <div className="container">
        <div className="reveal in">
          <div className="eyebrow">LEGAL</div>
          <h1>Privacy policy</h1>
          <div className="legal-meta">Last updated: May 8, 2026 · v1.0</div>
        </div>

        <div className="legal-grid">
          <aside className="legal-toc reveal">
            <h4>Contents</h4>
            {sections.map(s => (
              <a key={s.id} href={`#/privacy`} onClick={(e) => {
                e.preventDefault();
                document.getElementById(s.id)?.scrollIntoView({ behavior: "smooth", block: "start" });
              }}>{s.title}</a>
            ))}
          </aside>
          <div className="legal-content">
            <div className="legal-placeholder">
              ⚠ PLACEHOLDER COPY — replace each section below with your real, lawyer-reviewed policy text. Layout, table of contents, and section structure are ready.
            </div>

            <h2 id="overview">Overview</h2>
            <p>Cryptdapp is operated by <strong>2784951 Alberta Inc.</strong> (referred to as "Cryptdapp," "we," "us," "our"). This privacy policy explains what information our apps and website collect, how it's used, and your rights regarding it.</p>
            <p>This policy applies to: cryptdapp.com, Private Video Recorder, Motion Clock Camera, TrueTide, and Dual Camera.</p>

            <h2 id="what-we-collect">What we collect</h2>
            <p><em>[Replace with actual specifics for each app — e.g. for the website: the IP address that hits our analytics-free server logs (rotated every 14 days). For the apps: nothing leaves the device unless you explicitly enable cloud backup, in which case we collect [...]]</em></p>
            <ul>
              <li>Information you provide directly (e.g. when you contact us)</li>
              <li>Crash reports — only when you opt in</li>
              <li>Optional cloud backup data — only when you turn it on</li>
            </ul>

            <h2 id="what-we-don't">What we don't collect</h2>
            <p>We're loud about this because it's the whole point of the studio.</p>
            <ul>
              <li>No third-party analytics SDKs (no Google Analytics, no Mixpanel, no Firebase Analytics)</li>
              <li>No advertising identifiers</li>
              <li>No usage tracking — we don't know which features you use or how often</li>
              <li>No location, contacts, or microphone access unless an app's core feature requires it</li>
              <li>No selling, renting, or sharing your data with anyone — ever</li>
            </ul>

            <h2 id="where-data-lives">Where data lives</h2>
            <p><em>[Describe your hosting setup — region, encryption at rest, retention policy. Mention that media captured in our apps is stored locally on the user's device and is not transmitted unless explicitly shared.]</em></p>

            <h2 id="third-parties">Third parties</h2>
            <p><em>[List any third parties — e.g. App Store / Google Play handle in-app purchases on our behalf, your email provider receives any emails you send us. Crash reports (if enabled) go through [...].]</em></p>

            <h2 id="your-rights">Your rights</h2>
            <p>Depending on your jurisdiction (GDPR, CCPA, PIPEDA, etc.) you have rights to access, correct, delete, or export the data we hold about you. Email <a href="mailto:apps@cryptdapp.com" style={{color:"var(--brand-2)"}}>apps@cryptdapp.com</a> and we'll respond within 30 days.</p>

            <h2 id="changes">Changes to this policy</h2>
            <p>If we make material changes, we'll update the "last updated" date at the top of this page and, when relevant, post a notice in the affected app. Substantive changes get at least 14 days notice before they take effect.</p>

            <h2 id="contact">How to reach us</h2>
            <p><strong>2784951 Alberta Inc.</strong> (Cryptdapp)<br/>
            Privacy questions, data requests, or concerns: <a href="mailto:apps@cryptdapp.com" style={{color:"var(--brand-2)"}}>apps@cryptdapp.com</a>. For everything else, see the <a href="#/contact" style={{color:"var(--brand-2)"}}>contact page</a>.</p>
          </div>
        </div>
      </div>
    </div>
  );
};

window.ContactPage = ContactPage;
window.PrivacyPage = PrivacyPage;
