{{!< default}}
{{!--
  custom-contact.hbs — a contact page for any Ghost theme.
  From "How to Add a Real Contact Form to Ghost CMS" on ty1er.com.

  1. Save this file in your theme's root folder, upload the theme.
  2. In Ghost Admin, create a page and pick "Contact" under Template.
  3. The form posts to /contact-relay (send.php behind nginx).

  The <option> values below must match the $reasons list in send.php.
--}}

{{#post}}
<article class="contact-page">
    <header class="contact-header">
        <h1>{{title}}</h1>
        {{#if custom_excerpt}}<p>{{custom_excerpt}}</p>{{/if}}
    </header>

    {{content}}

    <div class="contact-card">
        <div class="contact-success" id="contact-success" role="status" aria-live="polite" tabindex="-1" hidden>
            <svg class="contact-success-check" viewBox="0 0 52 52" aria-hidden="true">
                <circle cx="26" cy="26" r="24" fill="none" stroke="currentColor" stroke-width="2.5"/>
                <path d="M15 27.5l7.5 7.5L38 19" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <h2>Message sent!</h2>
            <p>Thanks<span id="contact-success-name"></span>. Your message is on its way, and I'll get back to you soon.</p>
            <button type="button" id="contact-again">Send another message</button>
        </div>

        <form class="contact-form" id="contact-form" novalidate>
            <label for="cf-name">Name *</label>
            <input id="cf-name" name="name" type="text" autocomplete="name" required>

            <label for="cf-email">Email *</label>
            <input id="cf-email" name="email" type="email" autocomplete="email" required>

            <label for="cf-reason">Reason</label>
            <select id="cf-reason" name="reason">
                <option>General inquiry</option>
                <option>Project or consulting inquiry</option>
                <option>Partnership</option>
                <option>Something else</option>
            </select>

            <label for="cf-company">Company or website (optional)</label>
            <input id="cf-company" name="company" type="text">

            <label for="cf-message">Message *</label>
            <textarea id="cf-message" name="message" rows="6" required></textarea>

            {{!-- Honeypot: people never see or fill this; bots fill everything. --}}
            <div class="contact-hp" aria-hidden="true">
                <label for="cf-website">Leave this field empty</label>
                <input id="cf-website" name="website" type="text" tabindex="-1" autocomplete="off">
            </div>

            <button class="contact-submit" type="submit">Send message</button>
            <p class="contact-status" id="contact-status" role="status" aria-live="polite" hidden></p>
        </form>
    </div>
</article>
{{/post}}

<style>
    .contact-page { max-width: 680px; margin: 0 auto; padding: 48px 20px 80px; }
    .contact-form { display: grid; gap: 8px; }
    .contact-form input, .contact-form select, .contact-form textarea { width: 100%; box-sizing: border-box; padding: 11px 13px; font: inherit; border: 1px solid #ccd; border-radius: 8px; margin-bottom: 10px; }
    .contact-hp { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
    .contact-submit { justify-self: start; padding: 12px 24px; font: inherit; font-weight: 600; border: 0; border-radius: 8px; background: #111; color: #fff; cursor: pointer; }
    .contact-submit[disabled] { opacity: .6; cursor: wait; }
    .contact-status { margin: 8px 0 0; }
    .contact-status.is-err { color: #c62828; }
    .contact-success { text-align: center; padding: 32px 20px; border: 1.5px solid #16a34a; border-radius: 14px; background: #f0fdf4; color: #14532d; }
    .contact-success[hidden] { display: none; }
    .contact-success-check { width: 72px; height: 72px; color: #16a34a; }
    .contact-success button { padding: 10px 18px; font: inherit; border: 1px solid #16a34a; border-radius: 8px; background: transparent; cursor: pointer; }
</style>

<script>
(function () {
    var RELAY   = '/contact-relay';
    var form    = document.getElementById('contact-form');
    if (!form) return;
    var status  = document.getElementById('contact-status');
    var button  = form.querySelector('.contact-submit');
    var success = document.getElementById('contact-success');
    var token   = null;   // { t, sig }: the relay's signed "page loaded at" time

    function show(msg, ok) {
        status.hidden = false;
        status.textContent = msg;
        status.className = 'contact-status ' + (ok ? 'is-ok' : 'is-err');
    }

    // Ask the relay for a signed start time as soon as the page loads.
    function fetchToken() {
        return fetch(RELAY, { credentials: 'same-origin', cache: 'no-store' })
            .then(function (r) { return r.ok ? r.json() : null; })
            .then(function (j) { token = (j && j.sig) ? j : null; return token; })
            .catch(function () { token = null; return null; });
    }
    fetchToken();

    var ERRORS = {
        invalid:     'Please check your name, email, and message and try again.',
        expired:     'This form has been open a while. Please send it again.',
        rate:        'Too many messages from this connection. Please try again later.',
        unavailable: 'The form can’t be reached right now. Your message is still here, so please try again in a few minutes.'
    };

    function showSuccess(name) {
        document.getElementById('contact-success-name').textContent = name ? ', ' + name.split(/\s+/)[0] : '';
        status.hidden = true;
        form.hidden = true;
        success.hidden = false;
        success.scrollIntoView({ behavior: 'smooth', block: 'center' });
        success.focus({ preventScroll: true });
    }
    document.getElementById('contact-again').addEventListener('click', function () {
        success.hidden = true;
        form.hidden = false;
        form.reset();
        document.getElementById('cf-name').focus();
    });

    function send(tok) {
        var data = new URLSearchParams(new FormData(form));
        data.set('started_at', tok.t);
        data.set('started_sig', tok.sig);
        return fetch(RELAY, { method: 'POST', credentials: 'same-origin', body: data })
            .then(function (r) { return r.json().catch(function () { return {}; }); });
    }

    function handle(res, retried, name) {
        if (res.ok) { showSuccess(name); return; }
        if (res.error === 'expired' && !retried) {        // stale tab: new token, one retry
            return fetchToken().then(function (t) {
                return t ? send(t).then(function (r2) { return handle(r2, true, name); }) : show(ERRORS.unavailable, false);
            });
        }
        show(ERRORS[res.error] || ERRORS.unavailable, false);
    }

    form.addEventListener('submit', function (e) {
        e.preventDefault();
        if (form.website.value) { showSuccess(''); return; }   // honeypot: act normal, send nothing

        var name    = form.name.value.trim();
        var email   = form.email.value.trim();
        var message = form.message.value.trim();
        if (!name || !email || !message) { show('Please fill in your name, email, and a message.', false); return; }
        if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { show('That email address doesn’t look right. Please check it.', false); return; }

        button.disabled = true;
        show('Sending…', true);
        (token ? Promise.resolve(token) : fetchToken())
            .then(function (tok) { return tok ? send(tok).then(function (res) { return handle(res, false, name); }) : show(ERRORS.unavailable, false); })
            .catch(function () { show(ERRORS.unavailable, false); })
            .then(function () { button.disabled = false; fetchToken(); });
    });
})();
</script>
