/* FreeToolzHub — individual tool page. Mounts a REAL engine for working
   tools (PDF / Image / AI); shows a labelled DS demo flow otherwise. */
function fmtBytes(b){ return b<1024?b+' B':b<1048576?(b/1024).toFixed(1)+' KB':(b/1048576).toFixed(2)+' MB'; }

function ToolPage({ go, toolId, pushToast }) {
  const { Card, Icon, Badge, Button, UploadDropzone, ProgressBar, Tag } = window.DesignSystem_3a7ab0;
  const { byId, TONE_MAP, TOOLS } = window.FTH;
  const tool = byId(toolId);
  const [bg, fg] = TONE_MAP[tool.tone];
  const engineRef = React.useRef(null);

  // demo state (non-working tools)
  const [stage, setStage] = React.useState('idle');
  const [progress, setProgress] = React.useState(0);

  const engineFor = (t) => {
    if (window.SimpleTools && window.SimpleTools.has(t.id)) return { mount: (ctx)=>window.SimpleTools.mount(t.id, ctx) };
    if (window.AITools && window.AITools.REAL.has(t.id)) return window.AITools;
    if (window.PDFTools && window.PDFTools.REAL.has(t.id)) return window.PDFTools;
    if (window.ImageTools && window.ImageTools.REAL.has(t.id)) return window.ImageTools;
    return null;
  };

  React.useEffect(() => {
    setStage('idle'); setProgress(0);
    const eng = engineFor(tool);
    if (eng && engineRef.current) {
      eng.mount({
        want: tool.id, workspace: engineRef.current,
        toast: (m) => pushToast(m), fmtBytes, svg: window.svg,
      });
    }
  }, [toolId]);

  const startDemo = () => {
    setStage('processing'); setProgress(0);
    let p = 0;
    const t = setInterval(() => {
      p += Math.random()*18 + 6;
      if (p >= 100) { p = 100; clearInterval(t); setTimeout(()=>setStage('done'), 350); }
      setProgress(p);
    }, 240);
  };

  const isWorking = !!engineFor(tool);
  const related = TOOLS.filter(t => t.cat===tool.cat && t.id!==tool.id).slice(0,5);
  const relPool = related.length ? related : TOOLS.filter(t => t.id!==tool.id).slice(0,5);

  const steps = [
    ['upload-cloud','Upload','Drop your file or pick it from your device.'],
    ['sliders-horizontal','Adjust','Set options and preview the result live.'],
    ['download','Download','Save your clean file — no watermark, no wait.'],
  ];
  const benefits = [
    ['shield-check','No watermark, ever','Your exports are clean and professional — nothing added.'],
    ['lock','Private by design','Files are processed in your browser and never uploaded.'],
    ['zap','Blazing fast','Optimized to finish in seconds, even with large files.'],
    ['infinity','Always free','No trials, no caps, no premium lock.'],
  ];
  const faqs = [
    [`Is ${tool.title} really free?`, `Yes — it's 100% free with no usage limits, no trial, and no premium upgrade.`],
    [`Will my file have a watermark?`, `No. Your output is completely clean — FreeToolzHub never adds a watermark.`],
    [`Do I need to sign up?`, `No account required. Just open the tool and start working.`],
    [`Are my files safe?`, isWorking && tool.cat!=='ai' ? `Your file is processed entirely in your browser and never leaves your device.` : `We process securely and never store your files.`],
  ];

  return (
    <div style={{ background:'var(--bg-page)', minHeight:'80vh' }}>
      <div style={{ maxWidth:1140, margin:'0 auto', padding:'26px 24px 70px', display:'grid', gridTemplateColumns:'1fr 312px', gap:34, alignItems:'start' }} className="fth-tool-layout">
        {/* MAIN */}
        <div className="fth-page-enter">
          {/* breadcrumb */}
          <div style={{ display:'flex', alignItems:'center', gap:8, fontSize:13, color:'var(--text-muted)', marginBottom:20, flexWrap:'wrap' }}>
            <a onClick={()=>go('/')} style={{ cursor:'pointer', color:'var(--text-link)', fontWeight:600 }}>Home</a>
            <Icon name="chevron-right" size={14} />
            <a onClick={()=>go('/tools/'+tool.cat)} style={{ cursor:'pointer', color:'var(--text-link)', fontWeight:600 }}>{window.FTH.catLabel(tool.cat)}</a>
            <Icon name="chevron-right" size={14} /><span>{tool.title}</span>
          </div>

          {/* title */}
          <div style={{ display:'flex', alignItems:'flex-start', gap:16, marginBottom:10 }}>
            <span className="fth-tool-icon" style={{ ['--ic-bg']:bg, ['--ic-fg']:fg }}>
              <i className="fth-tic-shape a"></i><i className="fth-tic-shape b"></i><i className="fth-tic-shape c"></i>
              <Icon name={tool.icon} size={32} />
            </span>
            <div>
              <h1 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:32, color:'var(--text-strong)', margin:'2px 0 6px', letterSpacing:'-0.02em' }}>{tool.title}</h1>
              <p style={{ fontFamily:'var(--font-body)', fontSize:16, color:'var(--text-muted)', margin:0, maxWidth:520 }}>{tool.desc} Completely free, with no watermark and no sign-up.</p>
            </div>
          </div>
          <div style={{ display:'flex', gap:8, margin:'14px 0 22px', flexWrap:'wrap' }}>
            <Badge tone="success" icon="shield-check">No Watermark</Badge>
            <Badge tone="brand" icon="lock">Private</Badge>
            <Badge tone="teal" icon="zap">Instant</Badge>
          </div>

          {/* WORKSPACE */}
          <Card padding={26} style={{ borderRadius:'var(--radius-2xl)' }}>
            {isWorking ? (
              <div ref={engineRef} />
            ) : (
              <div>
                <div className="demo-note"><Icon name="info" size={18} /><span><b>Interactive demo.</b> This tool's processing isn't wired up in this build — the flow below previews the experience.</span></div>
                {stage==='idle' && (
                  <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
                    <UploadDropzone title="Drop your file here" hint="or click to browse" onFiles={startDemo} />
                    <Button variant="primary" size="lg" iconLeft="upload" onClick={startDemo} fullWidth>Choose file</Button>
                  </div>
                )}
                {stage==='processing' && (
                  <div style={{ display:'flex', flexDirection:'column', gap:18, padding:'14px 0' }}>
                    <Tag icon="file-text">your-file</Tag>
                    <ProgressBar value={progress} label="Processing…" showValue />
                    <p style={{ fontSize:13, color:'var(--text-faint)', margin:0 }}>Preview of the processing step.</p>
                  </div>
                )}
                {stage==='done' && (
                  <div style={{ display:'flex', flexDirection:'column', gap:18, alignItems:'center', textAlign:'center', padding:'10px 0' }}>
                    <span style={{ width:64, height:64, borderRadius:'var(--radius-full)', background:'var(--green-50)', color:'var(--green-600)', display:'grid', placeItems:'center' }}><Icon name="check" size={34} strokeWidth={3} /></span>
                    <h3 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:22, color:'var(--text-strong)', margin:0 }}>Preview ready</h3>
                    <p style={{ fontSize:14, color:'var(--text-muted)', margin:0 }}>This is a demo of the result step.</p>
                    <Button variant="secondary" size="md" iconLeft="rotate-ccw" onClick={()=>setStage('idle')}>Start over</Button>
                  </div>
                )}
              </div>
            )}
          </Card>

          {/* after-result ad */}
          <div style={{ marginTop:24 }}><window.FTHAdSlot label="728 × 90 — In-content" /></div>

          {/* how it works */}
          <section style={{ marginTop:44 }}>
            <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:24, color:'var(--text-strong)', margin:'0 0 18px' }}>How to use {tool.title}</h2>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16 }} className="fth-3col fth-anim-in">
              {steps.map((s,i)=>(
                <div key={i} style={{ position:'relative', padding:22, background:'var(--bg-card)', border:'1px solid var(--border-color)', borderRadius:'var(--radius-xl)' }}>
                  <span style={{ position:'absolute', top:16, right:20, fontFamily:'var(--font-heading)', fontWeight:800, fontSize:30, color:'var(--bg-subtle)' }}>{i+1}</span>
                  <span style={{ width:46, height:46, borderRadius:'var(--radius-md)', background:bg, color:fg, display:'grid', placeItems:'center', marginBottom:12 }}><Icon name={s[0]} size={22} /></span>
                  <strong style={{ fontFamily:'var(--font-heading)', fontSize:16, color:'var(--text-strong)', display:'block', marginBottom:5 }}>{s[1]}</strong>
                  <p style={{ fontFamily:'var(--font-body)', fontSize:14, color:'var(--text-muted)', margin:0 }}>{s[2]}</p>
                </div>
              ))}
            </div>
          </section>

          {/* benefits */}
          <section style={{ marginTop:40 }}>
            <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:24, color:'var(--text-strong)', margin:'0 0 18px' }}>Why use this tool</h2>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }} className="fth-2col fth-anim-in">
              {benefits.map((b,i)=>(
                <div key={i} style={{ display:'flex', gap:14, padding:20, background:'var(--bg-card)', border:'1px solid var(--border-color)', borderRadius:'var(--radius-xl)' }}>
                  <span style={{ width:44, height:44, borderRadius:'var(--radius-md)', background:bg, color:fg, display:'grid', placeItems:'center', flexShrink:0 }}><Icon name={b[0]} size={22} /></span>
                  <div><strong style={{ fontFamily:'var(--font-heading)', fontSize:15.5, color:'var(--text-strong)', display:'block', marginBottom:3 }}>{b[1]}</strong><p style={{ fontFamily:'var(--font-body)', fontSize:14, color:'var(--text-muted)', margin:0 }}>{b[2]}</p></div>
                </div>
              ))}
            </div>
          </section>

          {/* FAQ */}
          <section style={{ marginTop:40 }}>
            <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:24, color:'var(--text-strong)', margin:'0 0 18px' }}>FAQ</h2>
            <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
              {faqs.map((f,i)=><window.FTHFaqItem key={i} q={f[0]} a={f[1]} />)}
            </div>
          </section>
        </div>

        {/* SIDEBAR */}
        <aside style={{ display:'flex', flexDirection:'column', gap:22, position:'sticky', top:90 }} className="fth-tool-side fth-page-enter d1">
          <window.FTHAdSlot label="300 × 280" h={280} />
          <div style={{ padding:22, background:'var(--bg-card)', border:'1px solid var(--border-color)', borderRadius:'var(--radius-xl)' }}>
            <h3 style={{ fontFamily:'var(--font-heading)', fontSize:17, color:'var(--text-strong)', margin:'0 0 14px' }}>Related tools</h3>
            <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
              {relPool.map(t => {
                const [tb, tf] = TONE_MAP[t.tone];
                return (
                  <a key={t.id} onClick={()=>go('/tool/'+t.id)} style={{ display:'flex', alignItems:'center', gap:12, padding:10, borderRadius:'var(--radius-md)', cursor:'pointer' }}
                    onMouseEnter={e=>e.currentTarget.style.background='var(--bg-subtle)'} onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                    <span style={{ width:40, height:40, borderRadius:'var(--radius-md)', background:tb, color:tf, display:'grid', placeItems:'center', flexShrink:0 }}><Icon name={t.icon} size={20} /></span>
                    <span style={{ minWidth:0 }}>
                      <span style={{ display:'block', fontFamily:'var(--font-heading)', fontSize:14.5, color:'var(--text-strong)' }}>{t.title}</span>
                      <span style={{ display:'block', fontSize:12.5, color:'var(--text-muted)' }}>{window.FTH.catLabel(t.cat)}{t.working?' · Ready':''}</span>
                    </span>
                  </a>
                );
              })}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}
window.FTHToolPage = ToolPage;

/* shared FAQ item (also used on Home) */
window.FTHFaqItem = function FaqItem({ q, a }) {
  const { Icon } = window.DesignSystem_3a7ab0;
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ border:'1px solid var(--border-color)', borderRadius:'var(--radius-xl)', background:'var(--bg-card)', overflow:'hidden' }}>
      <button onClick={()=>setOpen(v=>!v)} style={{ width:'100%', textAlign:'left', padding:'18px 20px', display:'flex', justifyContent:'space-between', alignItems:'center', gap:14, background:'none', border:'none', cursor:'pointer', fontFamily:'var(--font-heading)', fontWeight:600, fontSize:16, color:'var(--text-strong)' }}>
        {q}<Icon name="chevron-down" size={18} style={{ transform: open?'rotate(180deg)':'none', transition:'transform var(--dur-base)', color:'var(--text-muted)' }} />
      </button>
      {open && <div style={{ padding:'0 20px 20px', fontFamily:'var(--font-body)', fontSize:15, color:'var(--text-muted)', lineHeight:1.6 }}>{a}</div>}
    </div>
  );
};
