/* Gridea site — /volitus : the e-elering access-right guide.
   Renders window.GRIDEA_VOLITUS (generated, per-language) in the site's current
   language. Served as a standalone page (volitus.html) so the URL is a clean,
   permanent gridea.io/volitus for emails and printed PDFs. Reuses the shared
   SiteNav / SiteFooter; nav/footer links do full navigation back to the SPA.
   Text fields contain limited inline HTML (<b>, <a>) — rendered as HTML. */

// UI chrome strings not part of the generated content (download button etc.).
const VOL_UI = {
  et: { eyebrow: 'Juhend', download: 'Lae alla PDF', pdfNote: 'Illustreeritud, prinditav ja edastatav versioon', missing: 'Sisu ei õnnestunud laadida. Palun laadi leht uuesti või kirjuta support@gridea.io.',
    openElering: 'Ava e‑elering', openEleringHint: 'Avaneb uues aknas — see juhend jääb siia avatuks, et saaksid samme kõrvalt jälgida.' },
  en: { eyebrow: 'Guide', download: 'Download PDF', pdfNote: 'Illustrated, printable, forwardable version', missing: 'Failed to load the content. Please reload the page or write to support@gridea.io.',
    openElering: 'Open e‑elering', openEleringHint: 'Opens in a new tab — this guide stays open here so you can follow the steps side by side.' },
  ru: { eyebrow: 'Инструкция', download: 'Скачать PDF', pdfNote: 'Иллюстрированная печатная версия для пересылки', missing: 'Не удалось загрузить содержимое. Пожалуйста, перезагрузите страницу или напишите на support@gridea.io.',
    openElering: 'Открыть e‑elering', openEleringHint: 'Откроется в новой вкладке — эта инструкция останется открытой, чтобы вы могли следовать шагам рядом.' },
};
const VOL_BENEFIT_ICONS = ['wallet', 'bell', 'shield-check', 'trend-up', 'mail', 'gauge'];
const VOL_PREP_ICONS = ['shield-check', 'building', 'clock'];

// e-elering (and any other external) links inside the generated guide text must
// open in a NEW TAB, so the guide stays open beside the Elering portal while the
// user grants access. The generated content ships plain <a href> without a target,
// so we inject it at render time rather than hand-editing the generated file.
// Internal gridea.io links are left in the same tab.
const EXT_LINK_RE = /<a\s+([^>]*href=(["'])(https?:\/\/[^"']+)\2[^>]*)>/gi;
const openExternalInNewTab = (html) => (typeof html === 'string'
  ? html.replace(EXT_LINK_RE, (m, attrs, _q, url) => {
      if (/\btarget=/i.test(attrs)) return m;                         // already set
      if (/^https?:\/\/(www\.)?gridea\.io/i.test(url)) return m;      // internal — same tab
      return `<a ${attrs} target="_blank" rel="noopener noreferrer">`;
    })
  : html);
const rawHtml = (s) => ({ dangerouslySetInnerHTML: { __html: openExternalInNewTab(s) } });

const ELERING_URL = 'https://estfeed.elering.ee';

function VolitusPdfBtn({ href, label, size }) {
  return (
    <a className={`btn btn-primary volitus-pdf-btn${size === 'lg' ? ' lg' : ''}`} href={href} target="_blank" rel="noopener noreferrer">
      <GIcon name="file-stack" size={16}/> {label}
    </a>
  );
}

// Opens the Elering portal in a new tab so the guide stays open beside it.
function EleringBtn({ label, size }) {
  return (
    <a className={`btn btn-primary volitus-elering-btn${size === 'lg' ? ' lg' : ''}`} href={ELERING_URL} target="_blank" rel="noopener noreferrer">
      <GIcon name="arrow-up-right" size={16}/> {label}
    </a>
  );
}

function VolitusPage() {
  const lang = useLang();
  const V = window.GRIDEA_VOLITUS || {};
  const T = V[lang] || V.et;
  const U = VOL_UI[lang] || VOL_UI.et;
  if (!T) return <section className="section light" style={{ minHeight: '50vh' }}><div className="container"><p>{U.missing}</p></div></section>;
  const pdf = '/' + T.pdf;

  return (
    <div className="route-page volitus-page">
      {/* Hero: title + intro + PDF (top) */}
      <section className="page-hero" style={{ paddingBottom: 32 }}>
        <div className="page-hero-inner">
          <span className="eyebrow">{U.eyebrow}</span>
          <h1 style={{ fontSize: 'clamp(28px, 3.4vw, 42px)' }} {...rawHtml(T.title)}/>
          <p {...rawHtml(T.lede)}/>
          <p className="volitus-sub" {...rawHtml(T.sub)}/>
          <div className="volitus-cta-row">
            <EleringBtn label={U.openElering}/>
            <VolitusPdfBtn href={pdf} label={U.download}/>
          </div>
          <p className="volitus-open-hint"><GIcon name="alert-circle" size={14}/> {U.openEleringHint}</p>
          <span className="volitus-pdf-note">{U.pdfNote}</span>
        </div>
      </section>

      {/* Benefits — why grant access */}
      <section className="section light volitus-section">
        <div className="container">
          <h2 className="volitus-h2" {...rawHtml(T.headings.benefits)}/>
          <div className="volitus-benefits">
            {T.benefits.map((b, i) => (
              <div className="volitus-benefit" key={i}>
                <div className="volitus-benefit-ico"><GIcon name={VOL_BENEFIT_ICONS[i] || 'check'} size={18}/></div>
                <div><h3 {...rawHtml(b.title)}/><p {...rawHtml(b.text)}/></div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Dark key-facts card — everything the person needs to type */}
      <section className="section light volitus-section">
        <div className="container">
          <div className="volitus-facts">
            <h2 className="volitus-facts-h" {...rawHtml(T.facts.heading)}/>
            <div className="volitus-facts-grid">
              {T.facts.items.map((it, i) => (
                <div className="volitus-fact" key={i}>
                  <div className="volitus-fact-label" {...rawHtml(it.label)}/>
                  <div className="volitus-fact-value" {...rawHtml(it.value)}/>
                </div>
              ))}
            </div>
            <p className="volitus-facts-hint" {...rawHtml(T.facts.hint)}/>
          </div>
        </div>
      </section>

      {/* Prep — what you need before starting */}
      <section className="section light volitus-section">
        <div className="container">
          <h2 className="volitus-h2" {...rawHtml(T.headings.prep)}/>
          <div className="volitus-prep">
            {T.prep.map((p, i) => (
              <div className="volitus-prep-item" key={i}>
                <GIcon name={VOL_PREP_ICONS[i] || 'check'} size={18}/>
                <div><strong {...rawHtml(p.title)}/><span {...rawHtml(p.text)}/></div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Steps */}
      <section className="section light volitus-section">
        <div className="container">
          <div className="volitus-steps">
            {T.steps.map((s) => (
              <div className="volitus-step" key={s.n}>
                <div className="volitus-step-n">{s.n}</div>
                <div className="volitus-step-body">
                  <h3 {...rawHtml(s.title)}/>
                  <p {...rawHtml(s.text)}/>
                </div>
              </div>
            ))}
          </div>
          <div className="volitus-illustr">
            <p {...rawHtml(T.illustrNote)}/>
            <div className="volitus-cta-row">
              <EleringBtn label={U.openElering}/>
              <VolitusPdfBtn href={pdf} label={U.download}/>
            </div>
            <p className="volitus-open-hint"><GIcon name="alert-circle" size={14}/> {U.openEleringHint}</p>
          </div>
        </div>
      </section>

      {/* What it grants / doesn't grant */}
      <section className="section light volitus-section">
        <div className="container">
          <h2 className="volitus-h2" {...rawHtml(T.headings.rights)}/>
          <div className="volitus-rights">
            <div className="volitus-rights-col grants">
              <h3><GIcon name="check-circle" size={16}/> <span {...rawHtml(T.grants.heading)}/></h3>
              <ul>{T.grants.items.map((it, i) => <li key={i} {...rawHtml(it)}/>)}</ul>
            </div>
            <div className="volitus-rights-col denies">
              <h3><span className="volitus-x">✕</span> <span {...rawHtml(T.denies.heading)}/></h3>
              <ul>{T.denies.items.map((it, i) => <li key={i} {...rawHtml(it)}/>)}</ul>
            </div>
          </div>
          <p className="volitus-revoke" {...rawHtml(T.revoke)}/>
        </div>
      </section>

      {/* FAQ */}
      <section className="section light volitus-section">
        <div className="container">
          <h2 className="volitus-h2" {...rawHtml(T.headings.faq)}/>
          <div className="volitus-faq">
            {T.faq.map((f, i) => (
              <div className="volitus-faq-item" key={i}>
                <h3 {...rawHtml(f.q)}/>
                <p {...rawHtml(f.a)}/>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Contacts + PDF (bottom) */}
      <section className="section light volitus-section">
        <div className="container">
          <div className="volitus-contacts">
            {T.contacts.map((c, i) => (
              <div className="volitus-contact" key={i}>
                <h3 {...rawHtml(c.title)}/>
                <p {...rawHtml(c.text)}/>
              </div>
            ))}
          </div>
          <div className="volitus-pdf-bottom">
            <VolitusPdfBtn href={pdf} label={U.download} size="lg"/>
            <span className="volitus-pdf-note">{U.pdfNote}</span>
          </div>
        </div>
      </section>
    </div>
  );
}

function VolitusApp() {
  // Standalone page — nav/footer links navigate back to the SPA at "/".
  const go = (r) => { window.location.href = (r === 'home') ? '/' : ('/#' + r); };
  return (
    <div data-screen-label="gridea-volitus">
      <SiteNav route={null} go={go}/>
      <VolitusPage/>
      <SiteFooter go={go}/>
    </div>
  );
}

window.VolitusApp = VolitusApp;
window.VolitusPage = VolitusPage;
