/* global React, Eyebrow, Icon */

/* ── PINNED FORMS ──────────────────────────────────────────────────────────
   Hidden hub, reachable only at  /#forms  (not in the nav).
   To add/edit a form: change an entry below.
   - url:   where the form lives (Microsoft Forms, Typeform, JotForm, etc.)
   - embed: true  → shows inline in an iframe on this page
            false → shows an "Open form →" button that opens url in a new tab
   ------------------------------------------------------------------------- */
const PINNED_FORMS = [
  {
    id: 'support-intake',
    tag: 'Support',
    title: 'Support / new-ticket intake',
    desc: 'For clients logging a request outside the portal. Captures priority, affected users, and what changed.',
    url: '',
    embed: false,
  },
  {
    id: 'offboarding',
    tag: 'Lifecycle',
    title: 'User offboarding request',
    desc: 'Leaver process — accounts to disable, data to retain, devices to reclaim, and the effective date.',
    url: '',
    embed: false,
  },
];

function FormCard({ f }) {
  const has = !!f.url;
  return (
    <div className="form-card">
      <div className="form-card-top">
        <span className="form-tag">{f.tag}</span>
        <h3>{f.title}</h3>
        <p>{f.desc}</p>
      </div>
      {f.embed && has ? (
        <div className="form-embed">
          <iframe title={f.title} src={f.url} loading="lazy"></iframe>
        </div>
      ) : (
        <div className="form-card-actions">
          {has ? (
            <a className="btn btn-primary btn-arrow" href={f.url} target="_blank" rel="noopener">
              Open form <Icon.arrow />
            </a>
          ) : (
            <span className="form-empty">No URL set — add one in <code>page-forms.jsx</code></span>
          )}
        </div>
      )}
    </div>
  );
}

const ONBOARDING_TO = 'onboarding@planetiware.com';

/* Access code handed to a client once they sign on. Client-side gate only —
   deters casual access; not real security. Change per intake if you like. */
const FORMS_ACCESS_CODE = 'planetiware-2026';

const AU_STATES = ['NSW', 'VIC', 'QLD', 'WA', 'SA', 'TAS', 'ACT', 'NT'];

/* Fields are ordered for a clean 2-col layout and tagged with `cw` — the
   ConnectWise Manage target (Company / Site / Contact) so a future backend
   can POST straight into CW. Static for now: submit composes an email. */
const OB_FIELDS = [
  { section: 'Business' },
  { id: 'legalName', label: 'Full legal / registered name', type: 'text', req: true, cw: 'company.name' },
  { id: 'tradingName', label: 'Trading name (if different)', type: 'text', cw: 'company.name (DBA)' },
  { id: 'abn', label: 'ABN', type: 'text', req: true, placeholder: '11 111 111 111', cw: 'company.customFields.ABN' },
  { id: 'acn', label: 'ACN (if a company)', type: 'text', cw: 'company.customFields.ACN' },
  { id: 'entityType', label: 'Entity type', type: 'select', options: ['Company (Pty Ltd)', 'Sole trader', 'Partnership', 'Trust', 'Not-for-profit', 'Government'], cw: 'company.type' },
  { id: 'industry', label: 'Industry', type: 'text', cw: 'company.marketId' },
  { id: 'staff', label: 'Headcount', type: 'text', placeholder: 'e.g. 220', cw: 'company.numberOfEmployees' },
  { id: 'website', label: 'Website', type: 'text', placeholder: 'https://', cw: 'company.website' },
  { id: 'mainPhone', label: 'Main phone', type: 'tel', cw: 'company.phoneNumber' },

  { section: 'Billing address' },
  { id: 'billLine1', label: 'Street address', type: 'text', req: true, full: true, cw: 'company.addressLine1' },
  { id: 'billLine2', label: 'Address line 2', type: 'text', full: true, cw: 'company.addressLine2' },
  { id: 'billSuburb', label: 'Suburb', type: 'text', cw: 'company.city' },
  { id: 'billState', label: 'State', type: 'select', options: AU_STATES, cw: 'company.state' },
  { id: 'billPostcode', label: 'Postcode', type: 'text', cw: 'company.zip' },
  { id: 'billCountry', label: 'Country', type: 'text', placeholder: 'Australia', cw: 'company.country' },

  { section: 'Primary site' },
  { id: 'siteName', label: 'Site name', type: 'text', placeholder: 'Head office', cw: 'site.name' },
  { id: 'siteSameAsBilling', label: 'Site address', type: 'select', options: ['Same as billing address', 'Different — enter below'], cw: 'site.addressLine1' },
  { id: 'siteLine1', label: 'Site street address', type: 'text', full: true, cw: 'site.addressLine1' },
  { id: 'siteSuburb', label: 'Site suburb', type: 'text', cw: 'site.city' },
  { id: 'siteState', label: 'Site state', type: 'select', options: AU_STATES, cw: 'site.state' },
  { id: 'sitePostcode', label: 'Site postcode', type: 'text', cw: 'site.zip' },
  { id: 'sitePhone', label: 'Site phone', type: 'tel', cw: 'site.phoneNumber' },
  { id: 'hoursDays', label: 'Business days', type: 'text', placeholder: 'Mon–Fri', cw: 'site.customFields.hours' },
  { id: 'hoursTime', label: 'Business hours', type: 'text', placeholder: '8:30am – 5:30pm', cw: 'site.customFields.hours' },

  { section: 'Primary contact' },
  { id: 'pcName', label: 'Full name', type: 'text', req: true, cw: 'contact[Primary].name' },
  { id: 'pcRole', label: 'Role / title', type: 'text', cw: 'contact[Primary].title' },
  { id: 'pcEmail', label: 'Email', type: 'email', req: true, cw: 'contact[Primary].email' },
  { id: 'pcPhone', label: 'Direct phone', type: 'tel', cw: 'contact[Primary].phone' },
  { id: 'pcMobile', label: 'Mobile', type: 'tel', cw: 'contact[Primary].mobile' },

  { section: 'Authorised approver', note: 'Who can approve work, changes and spend on the account.' },
  { id: 'apName', label: 'Approver name', type: 'text', cw: 'contact[Approver].name' },
  { id: 'apEmail', label: 'Approver email', type: 'email', cw: 'contact[Approver].email' },
  { id: 'apAuthority', label: 'Approval authority', type: 'select', options: ['All work & spend', 'Up to a limit', 'Change requests only'], cw: 'contact[Approver].customFields.authority' },
  { id: 'apLimit', label: 'Approval limit (if any)', type: 'text', placeholder: 'e.g. $5,000', cw: 'contact[Approver].customFields.limit' },

  { section: 'Billing contact' },
  { id: 'bcName', label: 'Billing contact name', type: 'text', cw: 'contact[Billing].name' },
  { id: 'bcEmail', label: 'Accounts / invoices email', type: 'email', cw: 'contact[Billing].email' },
  { id: 'poRequired', label: 'PO required on invoices?', type: 'select', options: ['No', 'Yes'], cw: 'company.customFields.poRequired' },

  { section: 'Environment & scope' },
  { id: 'tenant', label: 'Microsoft 365 tenant domain', type: 'text', placeholder: 'contoso.onmicrosoft.com', cw: 'company.customFields.tenant' },
  { id: 'licensing', label: 'Current licensing', type: 'text', placeholder: 'e.g. Business Premium ×180', cw: 'company.customFields.licensing' },
  { id: 'incumbent', label: 'Current IT provider (if any)', type: 'text', cw: 'company.customFields.incumbent' },
  { id: 'gostart', label: 'Target start date', type: 'date', cw: 'company.customFields.startDate' },
  { id: 'services', label: 'Services you want', type: 'text', full: true, placeholder: 'Managed IT, Intune, Security, Cloud, AI…', cw: 'company.customFields.services' },
  { id: 'notes', label: 'Anything else we should know', type: 'textarea', full: true, cw: 'company.customFields.notes' },
];

function OnboardingForm() {
  const [v, setV] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const set = (id) => (e) => setV((s) => ({ ...s, [id]: e.target.value }));

  const submit = (e) => {
    e.preventDefault();
    const lines = OB_FIELDS.filter((f) => f.id).map((f) => `${f.label}: ${v[f.id] || '—'}`);
    const body = encodeURIComponent('New customer onboarding\n\n' + lines.join('\n'));
    const subj = encodeURIComponent('Onboarding — ' + (v.legalName || 'new client'));
    window.location.href = `mailto:${ONBOARDING_TO}?subject=${subj}&body=${body}`;
    setSent(true);
  };

  return (
    <form className="ob-form" onSubmit={submit}>
      <div className="ob-grid">
        {OB_FIELDS.map((f, i) =>
          f.section ? (
            <div key={i} className="ob-sec full">
              <span>{f.section}</span>
              {f.note && <em>{f.note}</em>}
            </div>
          ) : (
            <label key={f.id} className={'ob-field' + (f.full || f.type === 'textarea' ? ' full' : '')}>
              <span>{f.label}{f.req && <em> *</em>}</span>
              {f.type === 'textarea' ? (
                <textarea rows="3" value={v[f.id] || ''} onChange={set(f.id)} placeholder={f.placeholder || ''}></textarea>
              ) : f.type === 'select' ? (
                <select value={v[f.id] || ''} onChange={set(f.id)}>
                  <option value="">Select…</option>
                  {f.options.map((o) => <option key={o} value={o}>{o}</option>)}
                </select>
              ) : (
                <input type={f.type} required={f.req} value={v[f.id] || ''} onChange={set(f.id)} placeholder={f.placeholder || ''} />
              )}
            </label>
          )
        )}
      </div>
      <div className="ob-actions">
        <button type="submit" className="btn btn-primary btn-arrow">Submit onboarding <Icon.arrow /></button>
        {sent && <span className="ob-sent">Opening your email client…</span>}
        <span className="form-empty">Submitting composes an email to <code>{ONBOARDING_TO}</code>. Swap for a real backend before launch.</span>
      </div>
    </form>
  );
}

function FormsGate({ children }) {
  const [ok, setOk] = React.useState(() => {
    try { return sessionStorage.getItem('pw_forms_ok') === '1'; } catch (e) { return false; }
  });
  const [code, setCode] = React.useState('');
  const [err, setErr] = React.useState(false);

  const submit = (e) => {
    e.preventDefault();
    if (code.trim().toLowerCase() === FORMS_ACCESS_CODE.toLowerCase()) {
      try { sessionStorage.setItem('pw_forms_ok', '1'); } catch (e2) {}
      setOk(true);
    } else {
      setErr(true);
    }
  };

  if (ok) return children;

  return (
    <main data-screen-label="Forms hub — locked">
      <div className="page-head">
        <div className="wrap">
          <Eyebrow>Client access only</Eyebrow>
          <h1>Onboarding</h1>
          <p className="lede">This area is shared once you have signed on. Enter the access code from your engagement email to continue.</p>
        </div>
      </div>
      <section className="tight" style={{background: 'var(--paper)'}}>
        <div className="wrap">
          <form className="forms-gate" onSubmit={submit}>
            <label className="ob-field">
              <span>Access code</span>
              <input type="password" autoFocus value={code}
                     onChange={(e) => { setCode(e.target.value); setErr(false); }}
                     className={err ? 'err' : ''} placeholder="Enter access code" />
            </label>
            <button type="submit" className="btn btn-primary btn-arrow">Unlock <Icon.arrow /></button>
            {err && <span className="forms-gate-err">That code is not right. Check your engagement email or contact us.</span>}
          </form>
        </div>
      </section>
    </main>
  );
}

function FormsPage() {
  return (
    <FormsGate>
    <main data-screen-label="Forms hub (hidden)">
      <div className="page-head">
        <div className="wrap">
          <Eyebrow>Internal · not linked</Eyebrow>
          <h1>Forms</h1>
          <p className="lede">
            A private hub for the forms we hand out — onboarding, intake, lifecycle. Reachable only at
            {' '}<code>/#forms</code>. Pin as many as you like by editing <code>page-forms.jsx</code>.
          </p>
        </div>
      </div>

      <section className="tight" style={{background: 'var(--paper)'}}>
        <div className="wrap">
          <div className="form-feature">
            <div className="form-feature-head">
              <span className="form-tag">Onboarding</span>
              <h2>New customer onboarding</h2>
              <p>Kick-off intake — company details, primary contacts, tenant and licensing, and the target start date. Takes about three minutes.</p>
            </div>
            <OnboardingForm />
          </div>

          <h3 className="forms-more">More forms</h3>
          <div className="forms-grid">
            {PINNED_FORMS.map((f) => <FormCard key={f.id} f={f} />)}
          </div>
        </div>
      </section>
    </main>
    </FormsGate>
  );
}

Object.assign(window, { FormsPage });
