// Logo Studio — a basic in-app logo creator (Settings → Branding).
//
// For tenants with no logo file at all: pick a brand color and a layout,
// type the business name, and get a clean PNG at the STANDARD sizes the
// rest of the app is formatted around (wide lockup 800×200, square mark
// 256×256 — the nav, PDFs, and email headers all scale these cleanly).
// Everything is drawn on a <canvas> client-side — no libraries, no network;
// the export is a normal PNG that rides the existing logo-library pipeline
// (same validation, same 400 KB / 2400px server guardrails as an upload).

// Standard export sizes — the "one size everything formats nicely around".
const LOGO_STD = { wide: { w: 800, h: 200 }, mark: { w: 256, h: 256 } };

const LOGO_STYLES = [
    { key: 'wordmark', label: 'Wordmark',     hint: 'Your name in your color' },
    { key: 'badge',    label: 'Badge + name', hint: 'Initials block beside the name' },
    { key: 'pill',     label: 'Pill',         hint: 'Name inside a filled pill' },
    { key: 'mark',     label: 'Square mark',  hint: 'Initials only — square' },
];

// Initials: first letter of up to 3 significant words ("KzNet Technologies" → KT).
const initialsOf = (name) =>
    (name || '').split(/\s+/).filter(w => /[a-z0-9]/i.test(w)).slice(0, 3).map(w => w[0].toUpperCase()).join('') || '?';

// Shrink font size until the text fits the box width.
const fitFont = (ctx, text, maxPx, startPx, weight = 700) => {
    let px = startPx;
    do {
        ctx.font = `${weight} ${px}px 'Helvetica Neue', Helvetica, Arial, sans-serif`;
        if (ctx.measureText(text).width <= maxPx) return px;
        px -= 2;
    } while (px > 12);
    return px;
};

// Draw one logo onto a canvas. Transparent background on purpose — the pill
// and badge carry their own fill, and the wordmark text uses the brand color,
// so the PNG sits on any theme. Returns nothing; caller exports the canvas.
function drawLogo(canvas, { style, name, tagline, color }) {
    const size = style === 'mark' ? LOGO_STD.mark : LOGO_STD.wide;
    canvas.width = size.w; canvas.height = size.h;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, size.w, size.h);
    ctx.textBaseline = 'middle';
    const ini = initialsOf(name);

    if (style === 'mark') {
        // Rounded square filled with the brand color, white initials.
        const r = 44;
        ctx.beginPath(); ctx.roundRect(8, 8, size.w - 16, size.h - 16, r); ctx.fillStyle = color; ctx.fill();
        ctx.fillStyle = '#ffffff'; ctx.textAlign = 'center';
        fitFont(ctx, ini, size.w - 90, 130, 800);
        ctx.fillText(ini, size.w / 2, size.h / 2 + 6);
        return;
    }

    if (style === 'pill') {
        ctx.beginPath(); ctx.roundRect(6, 30, size.w - 12, size.h - 60, (size.h - 60) / 2); ctx.fillStyle = color; ctx.fill();
        ctx.fillStyle = '#ffffff'; ctx.textAlign = 'center';
        fitFont(ctx, name, size.w - 120, 72, 700);
        ctx.fillText(name, size.w / 2, size.h / 2 + 2);
        return;
    }

    if (style === 'badge') {
        // Colored rounded square with initials, name (+ tagline) to its right.
        const box = size.h - 40;
        ctx.beginPath(); ctx.roundRect(10, 20, box, box, 28); ctx.fillStyle = color; ctx.fill();
        ctx.fillStyle = '#ffffff'; ctx.textAlign = 'center';
        fitFont(ctx, ini, box - 40, 80, 800);
        ctx.fillText(ini, 10 + box / 2, 20 + box / 2 + 4);
        const tx = box + 40, tw = size.w - tx - 16;
        ctx.fillStyle = color; ctx.textAlign = 'left';
        const namePx = fitFont(ctx, name, tw, 64, 700);
        if (tagline) {
            ctx.fillText(name, tx, size.h / 2 - 18);
            ctx.globalAlpha = 0.75;
            fitFont(ctx, tagline, tw, Math.min(30, namePx * 0.45), 500);
            ctx.fillText(tagline, tx, size.h / 2 + Math.max(26, namePx * 0.5));
            ctx.globalAlpha = 1;
        } else {
            ctx.fillText(name, tx, size.h / 2 + 2);
        }
        return;
    }

    // Wordmark (default): brand-color name, muted tagline underneath.
    ctx.fillStyle = color; ctx.textAlign = 'left';
    const namePx = fitFont(ctx, name, size.w - 32, 84, 700);
    if (tagline) {
        ctx.fillText(name, 16, size.h / 2 - 16);
        ctx.globalAlpha = 0.7;
        fitFont(ctx, tagline, size.w - 32, Math.min(32, namePx * 0.42), 500);
        ctx.fillText(tagline, 18, size.h / 2 + Math.max(30, namePx * 0.52));
        ctx.globalAlpha = 1;
    } else {
        ctx.fillText(name, 16, size.h / 2 + 2);
    }
}

const LogoStudioModal = ({ tenantName, defaultColor, canAdd, onAdd, onClose }) => {
    const [name, setName]       = React.useState(tenantName || '');
    const [tagline, setTagline] = React.useState('');
    const [style, setStyle]     = React.useState('badge');
    const [color, setColor]     = React.useState(defaultColor || '#2563eb');
    // Offscreen canvas → data URI in state; the preview strips are plain
    // <img>s so they can never race the draw (canvas isn't in the DOM at all).
    const canvasRef = React.useRef(document.createElement('canvas'));
    const [previewUri, setPreviewUri] = React.useState('');

    React.useEffect(() => {
        drawLogo(canvasRef.current, { style, name: name.trim() || 'Your Business', tagline: tagline.trim(), color });
        setPreviewUri(canvasRef.current.toDataURL('image/png'));
    }, [name, tagline, style, color]);

    const exportPng = () => previewUri;

    const handleDownload = () => {
        const a = document.createElement('a');
        a.href = exportPng();
        a.download = `${(name.trim() || 'logo').toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${style}.png`;
        a.click();
    };

    const handleAdd = () => { onAdd(exportPng(), `${name.trim() || 'Logo'} (${style})`); onClose(); };

    const size = style === 'mark' ? LOGO_STD.mark : LOGO_STD.wide;

    return (
        <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
            <div className="modal" style={{ maxWidth: 620 }}>
                <div className="modal-header">
                    <h3><i className="fas fa-wand-magic-sparkles" style={{ marginRight: '0.5rem' }}></i>Logo Studio</h3>
                    <button className="btn-icon" onClick={onClose}><i className="fas fa-times"></i></button>
                </div>
                <div className="modal-body">
                    <p className="form-hint" style={{ marginTop: 0 }}>
                        A quick, clean starter logo — pick a layout and color, and it exports at the
                        standard size ({size.w}×{size.h}px) that formats nicely everywhere in the CRM.
                    </p>

                    <div className="form-grid" style={{ marginBottom: '0.75rem' }}>
                        <div className="form-group">
                            <label className="form-label">Business name</label>
                            <input className="form-input" value={name} maxLength={60} onChange={e => setName(e.target.value)} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Tagline <span className="form-hint">(optional)</span></label>
                            <input className="form-input" value={tagline} maxLength={60} onChange={e => setTagline(e.target.value)}
                                   disabled={style === 'mark' || style === 'pill'} placeholder="Pro audio, done right" />
                        </div>
                    </div>

                    <div className="form-group" style={{ marginBottom: '0.75rem' }}>
                        <label className="form-label">Layout</label>
                        <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                            {LOGO_STYLES.map(s => (
                                <button key={s.key} type="button" title={s.hint}
                                        className={`filter-chip ${style === s.key ? 'active' : ''}`}
                                        onClick={() => setStyle(s.key)}>{s.label}</button>
                            ))}
                        </div>
                    </div>

                    <div className="form-group" style={{ marginBottom: '0.75rem' }}>
                        <label className="form-label">Brand color</label>
                        <ColorSwatchPicker value={color} onChange={setColor} />
                    </div>

                    {/* Preview on BOTH backgrounds — a logo that only reads on one theme
                        is a support ticket waiting to happen. */}
                    <label className="form-label">Preview</label>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                        {[['#10141c', 'dark'], ['#ffffff', 'light']].map(([bg, label]) => (
                            <div key={label} style={{ background: bg, border: '1px solid var(--border)', borderRadius: '0.5rem', padding: '0.75rem', display: 'flex', justifyContent: 'center' }}>
                                {previewUri && <img alt={`${label} preview`} src={previewUri} style={{ maxWidth: '100%', maxHeight: 90 }} />}
                            </div>
                        ))}
                    </div>
                </div>
                <div className="modal-footer">
                    <button className="btn btn-secondary" onClick={handleDownload}><i className="fas fa-download"></i> Download PNG</button>
                    <button className="btn btn-primary" onClick={handleAdd} disabled={!canAdd}
                            title={canAdd ? '' : 'Logo library is full — remove one first'}>
                        <i className="fas fa-plus"></i> Add to library
                    </button>
                </div>
            </div>
        </div>
    );
};
