/* global React, Icon, useSettings */
// ============================================================
// Info pages — About / Suggest / Report a bug / Contact / FAQ /
// Keyboard shortcuts / Disclaimer.
// ------------------------------------------------------------
// Rendered as a single full-screen overlay mounted at the app
// root (next to <DialogHost/>), opened from anywhere via the
// global window.openInfoPage('<id>'). Kept OUT of the tool
// router on purpose so these never appear in the sidebar,
// catalog, or ⌘K search.
// ============================================================

// Operator: point these at your real inbox before go-live.
const INFO_SUPPORT_EMAIL = 'hello@toolio.app';

const INFO_PAGES = [
  { id: 'about',      label: 'About',              icon: 'info',         group: 'Company' },
  { id: 'suggest',    label: 'Suggest a tool',     icon: 'lightbulb',    group: 'Company' },
  { id: 'bug',        label: 'Report a bug',       icon: 'bug_report',   group: 'Company' },
  { id: 'contact',    label: 'Contact',            icon: 'alternate_email', group: 'Company' },
  { id: 'faq',        label: 'FAQ',                icon: 'quiz',         group: 'Help' },
  { id: 'shortcuts',  label: 'Keyboard shortcuts', icon: 'keyboard',     group: 'Help' },
  { id: 'disclaimer', label: 'Disclaimer',         icon: 'gavel',        group: 'Legal' },
];

// ---------- small building blocks ----------
function Kbd({ children }) {
  return <kbd className="info-kbd">{children}</kbd>;
}

function InfoField({ label, hint, children }) {
  return (
    <label className="info-field">
      <span className="info-field-label">{label}{hint && <em>{hint}</em>}</span>
      {children}
    </label>
  );
}

// Reusable mailto form used by Suggest / Bug / Contact.
function InfoMailForm({ subjectPrefix, fields, buttonLabel, brand, includeEnvOption }) {
  const [vals, setVals] = useState(() => Object.fromEntries(fields.map(f => [f.name, ''])));
  const [includeEnv, setIncludeEnv] = useState(!!includeEnvOption);
  const [sent, setSent] = useState(null);
  const set = (name, v) => setVals(p => ({ ...p, [name]: v }));

  const required = fields.filter(f => f.required).map(f => f.name);
  const valid = required.every(n => (vals[n] || '').trim().length > 0);

  const buildMailto = () => {
    const lead = vals[fields[0].name] || '';
    const subject = `${subjectPrefix}${lead ? ': ' + lead.slice(0, 64) : ''}`;
    let body = fields.map(f => `${f.label}:\n${(vals[f.name] || '').trim() || '—'}`).join('\n\n');
    if (includeEnv) {
      body += `\n\n— — —\nApp: ${brand}\nURL: ${location.href}\nBrowser: ${navigator.userAgent}\nViewport: ${window.innerWidth}×${window.innerHeight}`;
    }
    return `mailto:${INFO_SUPPORT_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  };

  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    const url = buildMailto();
    setSent(url);
    window.location.href = url;
  };

  if (sent) {
    return (
      <div className="info-sent">
        <span className="info-sent-icon"><Icon name="mark_email_read" /></span>
        <div className="info-sent-title">Your email app should be opening…</div>
        <p className="info-sent-sub">
          We don’t run a server, so messages are sent straight from your own email
          client to our team. If nothing opened, use the button below.
        </p>
        <div className="info-sent-actions">
          <a className="lh-btn primary" href={sent}>Open email app</a>
          <button className="lh-btn ghost" onClick={() => setSent(null)}>Back to form</button>
        </div>
      </div>
    );
  }

  return (
    <form className="info-form" onSubmit={submit}>
      {fields.map(f => (
        <InfoField key={f.name} label={f.label} hint={f.required ? null : ' (optional)'}>
          {f.type === 'textarea'
            ? <textarea className="lh-input info-textarea" rows={f.rows || 4} placeholder={f.placeholder}
                value={vals[f.name]} onChange={e => set(f.name, e.target.value)} />
            : <input className="lh-input" type={f.type || 'text'} placeholder={f.placeholder}
                value={vals[f.name]} onChange={e => set(f.name, e.target.value)} />}
        </InfoField>
      ))}
      {includeEnvOption && (
        <label className="info-check">
          <input type="checkbox" checked={includeEnv} onChange={e => setIncludeEnv(e.target.checked)} />
          <span>Attach my browser &amp; screen info (helps us reproduce the bug)</span>
        </label>
      )}
      <div className="info-form-foot">
        <button type="submit" className="lh-btn primary" disabled={!valid}>
          <Icon name="send" />{buttonLabel}
        </button>
        <span className="info-form-note">Opens your email app · nothing is uploaded</span>
      </div>
    </form>
  );
}

// ---------- the seven pages ----------
function InfoAbout({ brand }) {
  const stats = [
    { icon: 'lock', title: '100% private', sub: 'Everything runs in your browser. Your files and data never touch a server.' },
    { icon: 'bolt', title: 'No sign-up', sub: 'No account, no email wall, no tracking. Open a tool and start using it.' },
    { icon: 'favorite', title: 'Always free', sub: 'Every tool is free to use, with no usage caps or paywalled features.' },
  ];
  return (
    <div className="info-page">
      <h1 className="info-h1">About {brand}</h1>
      <p className="info-lead">
        {brand} is a free collection of everyday online tools — for PDFs, images,
        video, text, code and more — that all run right inside your browser.
      </p>
      <div className="info-stats">
        {stats.map(s => (
          <div className="info-stat" key={s.title}>
            <span className="info-stat-icon"><Icon name={s.icon} /></span>
            <div className="info-stat-title">{s.title}</div>
            <div className="info-stat-sub">{s.sub}</div>
          </div>
        ))}
      </div>
      <h2 className="info-h2">How it works</h2>
      <p className="info-p">
        Most online utilities upload your files to a server to process them. {brand}
        takes the opposite approach: the tools execute locally on your own device, so
        your documents, photos and notes stay with you. Anything you save — notes,
        bookmarks, settings — lives in this browser’s local storage and is never
        synced anywhere.
      </p>
      <h2 className="info-h2">Why we built it</h2>
      <p className="info-p">
        We were tired of juggling a dozen sketchy single-purpose sites, each plastered
        with ads and pop-ups, just to convert a file or generate a password. {brand}
        brings the tools you reach for most into one fast, quiet, privacy-respecting
        place — and we keep adding more.
      </p>
      <div className="info-cta">
        <button className="lh-btn primary" onClick={() => window.openInfoPage('suggest')}>
          <Icon name="lightbulb" />Suggest a tool
        </button>
        <button className="lh-btn ghost" onClick={() => window.openInfoPage('faq')}>
          <Icon name="quiz" />Read the FAQ
        </button>
      </div>
    </div>
  );
}

function InfoSuggest({ brand }) {
  return (
    <div className="info-page">
      <h1 className="info-h1">Suggest a tool</h1>
      <p className="info-lead">
        Missing something you’d use? Tell us what it is and we’ll consider it for a
        future release. The most-requested tools get built first.
      </p>
      <InfoMailForm
        brand={brand}
        subjectPrefix="Tool suggestion"
        buttonLabel="Send suggestion"
        fields={[
          { name: 'tool', label: 'What tool would you like?', required: true, placeholder: 'e.g. PDF page reorder, EXIF viewer…' },
          { name: 'detail', label: 'What should it do?', type: 'textarea', required: true, rows: 5, placeholder: 'Describe the job you’d use it for.' },
          { name: 'email', label: 'Your email', type: 'email', placeholder: 'So we can follow up if needed' },
        ]}
      />
    </div>
  );
}

function InfoBug({ brand }) {
  return (
    <div className="info-page">
      <h1 className="info-h1">Report a bug</h1>
      <p className="info-lead">
        Something not working right? Let us know what happened and we’ll get on it.
        Clear steps to reproduce help us fix things faster.
      </p>
      <InfoMailForm
        brand={brand}
        subjectPrefix="Bug report"
        buttonLabel="Send report"
        includeEnvOption
        fields={[
          { name: 'summary', label: 'What went wrong?', required: true, placeholder: 'A short summary of the problem' },
          { name: 'tool', label: 'Which tool?', placeholder: 'e.g. Image converter' },
          { name: 'steps', label: 'Steps to reproduce', type: 'textarea', rows: 5, placeholder: '1. Opened…\n2. Clicked…\n3. Saw…' },
          { name: 'email', label: 'Your email', type: 'email', placeholder: 'So we can let you know it’s fixed' },
        ]}
      />
    </div>
  );
}

function InfoContact({ brand }) {
  return (
    <div className="info-page">
      <h1 className="info-h1">Contact us</h1>
      <p className="info-lead">
        Questions, feedback or partnership ideas? We read every message and usually
        reply within a couple of business days.
      </p>
      <a className="info-emailcard" href={`mailto:${INFO_SUPPORT_EMAIL}`}>
        <span className="info-emailcard-icon"><Icon name="alternate_email" /></span>
        <span className="info-emailcard-text">
          <span className="info-emailcard-label">Email us directly</span>
          <span className="info-emailcard-value">{INFO_SUPPORT_EMAIL}</span>
        </span>
        <Icon name="arrow_outward" className="info-emailcard-go" />
      </a>
      <div className="info-divider"><span>or send a message</span></div>
      <InfoMailForm
        brand={brand}
        subjectPrefix="Message"
        buttonLabel="Send message"
        fields={[
          { name: 'name', label: 'Your name', placeholder: 'Jane Doe' },
          { name: 'email', label: 'Your email', type: 'email', required: true, placeholder: 'jane@example.com' },
          { name: 'message', label: 'Message', type: 'textarea', required: true, rows: 5, placeholder: 'How can we help?' },
        ]}
      />
    </div>
  );
}

function InfoFaq({ brand }) {
  const faqs = [
    { q: `Is ${brand} really free?`, a: `Yes. Every tool is free to use with no usage limits, trials or paywalled features. There are no ads either.` },
    { q: 'Do I need to create an account?', a: 'No. There’s no sign-up and no login. Just open a tool and start — nothing is gated behind an email address.' },
    { q: 'Where is my data stored?', a: 'Anything you save — notes, bookmarks, settings, history — is kept in your browser’s local storage on this device. It is not uploaded to a server or synced between devices.' },
    { q: 'Do my files get uploaded anywhere?', a: 'No. The tools process your files locally in the browser, so your documents and images never leave your device.' },
    { q: 'Can I use it offline?', a: 'Once the page has loaded, most tools keep working without a connection, since the processing happens on your device.' },
    { q: 'How do I clear my data?', a: 'Clearing your browser’s site data for this page removes everything stored locally. There is nothing for us to delete on our end, because we never received it.' },
    { q: 'Which browsers are supported?', a: 'Any modern, up-to-date browser — Chrome, Edge, Firefox, Safari and Brave — on desktop or mobile.' },
    { q: 'How do I request a tool or report a problem?', a: 'Use the “Suggest a tool” and “Report a bug” pages, linked from this panel and in the footer. We read every submission.' },
  ];
  return (
    <div className="info-page">
      <h1 className="info-h1">Frequently asked questions</h1>
      <p className="info-lead">The short answers to what people ask most.</p>
      <div className="info-faq">
        {faqs.map((f, i) => (
          <details className="info-faq-item" key={i}>
            <summary>
              <span>{f.q}</span>
              <Icon name="expand_more" className="info-faq-chevron" />
            </summary>
            <p>{f.a}</p>
          </details>
        ))}
      </div>
    </div>
  );
}

function InfoShortcuts() {
  const groups = [
    { title: 'Global', rows: [
      { keys: ['⌘', 'K'], desc: 'Open / close search' },
      { keys: ['⌘', ','], desc: 'Open / close settings' },
    ] },
    { title: 'Search palette', rows: [
      { keys: ['↑'], desc: 'Move selection up' },
      { keys: ['↓'], desc: 'Move selection down' },
      { keys: ['↵'], desc: 'Open the highlighted result' },
      { keys: ['Esc'], desc: 'Close search' },
    ] },
    { title: 'Anywhere', rows: [
      { keys: ['Esc'], desc: 'Close this panel and other dialogs' },
    ] },
  ];
  return (
    <div className="info-page">
      <h1 className="info-h1">Keyboard shortcuts</h1>
      <p className="info-lead">
        Move faster without the mouse. On Windows and Linux, use <Kbd>Ctrl</Kbd> wherever
        you see <Kbd>⌘</Kbd>.
      </p>
      <div className="info-shortcuts">
        {groups.map(g => (
          <div className="info-shortcut-group" key={g.title}>
            <h2 className="info-h2">{g.title}</h2>
            <div className="info-shortcut-rows">
              {g.rows.map((r, i) => (
                <div className="info-shortcut-row" key={i}>
                  <span className="info-shortcut-keys">
                    {r.keys.map((k, j) => <Kbd key={j}>{k}</Kbd>)}
                  </span>
                  <span className="info-shortcut-desc">{r.desc}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function InfoDisclaimer({ brand }) {
  const today = new Date().toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });
  const sections = [
    { h: 'General', p: `${brand} and its tools are provided on an “as is” and “as available” basis, for general informational and productivity purposes. By using the service you accept this disclaimer in full.` },
    { h: 'No warranty', p: `We make no warranties, express or implied, about the reliability, accuracy, completeness or availability of the tools. To the fullest extent permitted by law, ${brand} disclaims all such warranties.` },
    { h: 'Accuracy of results', p: 'Tools such as converters, calculators and generators are offered as conveniences. Always verify any output before relying on it for important, legal, financial, medical or safety-critical decisions.' },
    { h: 'Your data &amp; your responsibility', p: 'Your data is stored locally in your own browser. You are responsible for keeping your own backups; clearing your browser data or switching devices will remove anything saved here, and it cannot be recovered by us.' },
    { h: 'Limitation of liability', p: `In no event shall ${brand}, its makers or contributors be liable for any loss or damage — including lost data, lost profits, or business interruption — arising from your use of, or inability to use, the service.` },
    { h: 'External links', p: 'Some pages may link to third-party sites. We are not responsible for the content, policies or practices of any external site, and a link does not imply endorsement.' },
    { h: 'Changes', p: 'We may update these terms from time to time. Continued use of the service after changes are posted constitutes acceptance of the revised disclaimer.' },
  ];
  return (
    <div className="info-page">
      <h1 className="info-h1">Disclaimer</h1>
      <p className="info-lead">Last updated {today}.</p>
      <div className="info-legal">
        {sections.map((s, i) => (
          <section key={i}>
            <h2 className="info-h2" dangerouslySetInnerHTML={{ __html: s.h }} />
            <p className="info-p" dangerouslySetInnerHTML={{ __html: s.p }} />
          </section>
        ))}
      </div>
    </div>
  );
}

const INFO_COMPONENTS = {
  about: InfoAbout,
  suggest: InfoSuggest,
  bug: InfoBug,
  contact: InfoContact,
  faq: InfoFaq,
  shortcuts: InfoShortcuts,
  disclaimer: InfoDisclaimer,
};

// ---------- host overlay ----------
function InfoPagesHost() {
  const [settings] = useSettings();
  const [open, setOpen] = useState(null);
  const brand = settings.appTitle || 'Toolio';

  useEffect(() => {
    window.openInfoPage = (id) => setOpen(INFO_COMPONENTS[id] ? id : 'about');
    return () => { delete window.openInfoPage; };
  }, []);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(null); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [open]);

  if (!open) return null;
  const Page = INFO_COMPONENTS[open] || InfoAbout;
  const groups = [...new Set(INFO_PAGES.map(p => p.group))];

  return (
    <div className="info-overlay" onClick={() => setOpen(null)}>
      <div className="info-shell" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true">
        <header className="info-shell-head">
          <div className="info-shell-brand">
            <span className="info-shell-tile"><Icon name={settings.brandIcon || 'grid_view'} /></span>
            <span className="info-shell-title">Help &amp; information</span>
          </div>
          <button className="info-shell-close" onClick={() => setOpen(null)} title="Close (Esc)">
            <Icon name="close" />
          </button>
        </header>
        <div className="info-shell-body">
          <nav className="info-nav" aria-label="Pages">
            {groups.map(g => (
              <div className="info-nav-group" key={g}>
                <div className="info-nav-grouplabel">{g}</div>
                {INFO_PAGES.filter(p => p.group === g).map(p => (
                  <button
                    key={p.id}
                    className={`info-nav-item ${open === p.id ? 'is-active' : ''}`}
                    onClick={() => setOpen(p.id)}
                  >
                    <Icon name={p.icon} />
                    <span>{p.label}</span>
                  </button>
                ))}
              </div>
            ))}
          </nav>
          <div className="info-content" key={open}>
            <Page brand={brand} />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InfoPagesHost });
