// Slide-request card — sends users to a hosted Zoho Form in a new tab.
//
// Zoho Forms handles capture + consent storage + direct sync into Zoho
// Campaigns (where an autoresponder emails the deck). The Companion App
// just provides a clean handoff: a styled card on the close page with a
// single "Get the slides →" button that opens the form in a new tab.
//
// Configuration (in Tweaks):
//   slidesFormUrl — public Zoho Form URL (e.g. https://forms.zoho.com/…/EduPulse_Slides)
//   eventName     — prefilled into the form via ?eventName=…
//                   (set the matching field in Zoho Forms to "prefill from URL")
//
// If slidesFormUrl is not set, the card shows a presenter-setup note and
// falls back to a mailto: link to contactEmail so the close screen is never
// dead.

function SlidesEmailCapture() {
  const tweaks = window.TWEAK_DEFAULTS || {};
  const formUrl = (tweaks.slidesFormUrl || "").trim();
  const contactEmail = tweaks.contactEmail || "info@truenorth-zone.com";
  const eventName = tweaks.eventName || "The Stress Reset";

  // Build the URL with eventName prefilled. Zoho Forms accepts URL params
  // when the form's field is configured to "prefill from URL"; if it's not,
  // the extra param is simply ignored. Safe to always include.
  const targetUrl = React.useMemo(() => {
    if (!formUrl) return "";
    try {
      const u = new URL(formUrl);
      u.searchParams.set("eventName", eventName);
      return u.toString();
    } catch (_e) {
      return formUrl;
    }
  }, [formUrl, eventName]);

  // Fallback: mailto if no form URL is configured.
  const mailtoFallback = React.useMemo(() => {
    const subject = encodeURIComponent("Please send me the slides — " + eventName);
    const body = encodeURIComponent(
      "Hello,\n\n" +
      "Please send me the slide deck from " + eventName + ".\n\n" +
      "Name: \n" +
      "Email: \n" +
      "Organisation (optional): \n\n" +
      "Marketing opt-in (yes/no): \n\n" +
      "Thank you."
    );
    return "mailto:" + contactEmail + "?subject=" + subject + "&body=" + body;
  }, [contactEmail, eventName]);

  const href = targetUrl || mailtoFallback;
  const isMailtoFallback = !targetUrl;

  return (
    <div className="ec-card">
      <div className="ec-eyebrow">Get the slides by email</div>
      <h4 className="ec-title">Want a copy of the deck?</h4>
      <p className="ec-lede">
        Slides aren't downloadable from this app. Pop your details in our short
        form and we'll email the deck to your inbox — usually within a few
        hours, latest within 24.
      </p>

      <a
        className="ec-submit ec-submit-link"
        href={href}
        target={isMailtoFallback ? undefined : "_blank"}
        rel={isMailtoFallback ? undefined : "noopener noreferrer"}
      >
        {isMailtoFallback ? "Email us for the slides →" : "Get the slides →"}
      </a>

      <p className="ec-form-foot">
        {isMailtoFallback ? (
          <>Opens your email app. No tracking — just a direct message to our inbox.</>
        ) : (
          <>Opens a short, secure form in a new tab. Two questions and a tickbox — done in under a minute.</>
        )}
      </p>

      <div className="ec-privacy">
        <span className="ec-privacy-icon" aria-hidden="true">
          <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="3" y="11" width="18" height="11" rx="2"/>
            <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
          </svg>
        </span>
        <span>
          Your email is used only to send the slides (and, if you tick the
          marketing box on the form, occasional updates about future sessions
          and resources). We never share or sell your details. Unsubscribe any
          time.
        </span>
      </div>

      {isMailtoFallback && (
        <div className="ec-config-note">
          <strong>Presenter setup needed:</strong> set <code>slidesFormUrl</code> in Tweaks to your public Zoho Form URL. Until then, this button opens the user's email client as a fallback.
        </div>
      )}
    </div>
  );
}

// ── Single-click "ask a question" card ────────────────────────────────────
function AskQuestionCard() {
  const tweaks = window.TWEAK_DEFAULTS || {};
  const contactEmail = tweaks.contactEmail || "info@truenorth-zone.com";
  const eventName = tweaks.eventName || "The Stress Reset";

  const [marketingOptIn, setMarketingOptIn] = React.useState(false);

  const openEmail = () => {
    const subject = encodeURIComponent("Question after " + eventName);
    const body = encodeURIComponent(
      "Hello,\n\n" +
      "[Type your question here]\n\n\n" +
      "— sent from the " + eventName + " companion app.\n" +
      "Marketing opt-in: " + (marketingOptIn ? "YES — happy to receive future sessions, tools and content" : "No, this question only") + "\n"
    );
    window.location.href = "mailto:" + contactEmail + "?subject=" + subject + "&body=" + body;
  };

  return (
    <div className="ask-card">
      <div className="ask-head">
        <div className="ask-mark">?</div>
        <div>
          <div className="ask-title">Still have a question?</div>
          <div className="ask-sub">
            Click below to email us. We read every message and reply within a few working days.
          </div>
        </div>
      </div>

      <label className="ask-consent">
        <input
          type="checkbox"
          checked={marketingOptIn}
          onChange={(e) => setMarketingOptIn(e.target.checked)}
        />
        <span>
          <strong>I also consent to marketing emails</strong> — occasional updates
          about future sessions, free resources, and tools for stress and wellbeing.
          (Unsubscribe any time. Optional — your question will still get answered
          if you leave this unticked.)
        </span>
      </label>

      <button className="ask-btn" onClick={openEmail}>
        <span className="ask-btn-icon" aria-hidden="true">✉</span>
        <span>Click here to ask →</span>
      </button>

      <p className="ask-foot">
        Your message opens in your email app. We reply within a few working days.
      </p>
    </div>
  );
}

Object.assign(window, { SlidesEmailCapture, AskQuestionCard });
